Passport.js Authentication

What is middleware Authentication and why it is important?

Middleware Authentication is the technique used to ensure that the managing server and data collectors communicate with each other in a secure manner.

lets give a simple example:

suppose we have create a api end point and host it.

app.get('/users', usersController.getUsers);

Now, this end point ‘/users’ can be exposed by publicly. Anyone have to access the users data. In this point, if we want to restrict the access the end-point. The end-point will be accessed by registered users. For that, we need set a middleware authentication and this middleware will ensure us to proper access right.

app.get('/users', passport.ensureAuthenticated, usersController.getUsers);

See the above route, we have placed a middleware ‘passport.ensureAuthenticated’. Basically ‘ensureAuthenticated’ is a function and we will discuss about this later.

passport.ensureAuthenticated = function (req, res, next) {
//....
}

Passport.js

Passport.js is one of the flexible authentication middleware for Node.js. It is designed to serve a singular purpose: authenticate requests. When writing modules, encapsulation is a virtue, so Passport delegates all other functionality to the application. This separation of concerns keeps code clean and maintainable, and makes Passport extremely easy to integrate into an application. Read more

The most widely used way for websites to authenticate users is via a username and password. Support for this mechanism is provided by the passport-local module. This Local Strategy allows us to authenticate users by looking up their data in the app’s database.

In this post- i am going to explain authentication flow and later post i will give a complete guideline for implementing it with source code.

Authentication flow

    1. When the user submits the login form, a POST request to /login is made resulting in the execution of the passport.authenticate middleware we’ve set up.
      passport.authenticate('local', {
        successRedirect: '/homePage',
        failureRedirect: '/loginFail',
        failureFlash: false
      })(req, res, next);
    2. As the authenticate middleware for that route is configured to handle the local strategy, passport will invoke our implementation of the local strategy.
      passport.use(new LocalStrategy(User.authenticate()));
    3. Passport takes the req.body.username and req.body.password and passes it to our verification function in the local strategy.
    4. Now we do our thing: loading the user from the database and checking if the password given matches the one in the database.
    5. If the user was passed, then this will call our passport.serializeUser method we’ve defined earlier. This method can access the user object we passed back to the middleware. We can define here what object should be stored in session.
      passport.serializeUser(function (user, done) {
          done(null, {username: user.username});
      });

      The result of the serializeUser method is attached to the session as req.session.passport.user = { username: ‘username’ }.
      The result is also attached to the request as req.user.

    6. Once done, our requestHandler is invoked. In the example the user is redirected to the homepage.

Middleware (subsequence request) Authentication flow

  1. Express loads the session data and attaches it to the req. As passport stores the serialized user in the session, the serialized user object can be found at
    req.session.passport.user.
  2. Next, passport.session is invoked. This middleware is a Passport Strategy invoked on every request. If it finds a serialized user object in the session, it will consider this request authenticated.
  3. The passport.session middleware calls passport.deserializeUser we’ve setup. Attaching the loaded user object to the request as req.user. When deserializeUser is called then we can able to customize the user object.
    passport.deserializeUser(function (user, done) {
      UserProfile.findOne({username: user.username}).then(user => {
          done(null, user);
        }).catch(err => {
          done(err);
         })
    });

 

You May Also Like

About the Author: Md. Delwar Hossain

He has 11 years of experience in developing standalone software and web applications for multiple database platforms. He has been passionate about new tools and technologies. He is positive and trustworthy. He is capable to learn and adapt quickly to different situations. He is a great team player and enjoys leading and mentoring. He is specialized in architecting and building complex web and mobile application. He has strong skills to automate POS, inventory, supply chain, trading export/ import, human resource management, manufacturing and production, distribution management system and hospital management system.

Leave a Reply

Your email address will not be published. Required fields are marked *