Learn node js, angular, php best practices. A self learning platform to learn web development. Learn modern web development technologies.

August 24, 2019

A Complete Guide To Passport JS Part 1


Complete guide to passport js part 1


In simple words, passport js is a middleware for the express js framework. It allows developers to integrate different types of authentication strategies with very little amount of code. For example: developers can add various types of sign in functionality with different services like google, facebook, twitter, github etc, also developers can add their own custom strategy by authenticating users with email and password.

We can also combine all of the strategies so that users can login with any one of the selected strategies. It is much quicker to use passport js rather than building a custom authentication strategy from scratch.

When I first started working with passport js, it took me several days to fully understand the inner-workings of it. I went through the official documentation, searched for tutorials, looked in stack overflow for help, after doing all these extra work I was able to understand it.


Topics Covered In This Article


  1. Setting up callback function for configuring passport strategy.
  2. Importance of passport.authenticate() function in callback url.
  3. Setting up middleware to check if a user is already logged in or not.
  4. How serializeUser() and deserializeUser() actually works.
  5. A sample application that will connect all these points practically that are discussed in this article.

Ok, so let's get started.

Setting up callback function for configuring passport strategy


Take a look at the code below. Here, we have required the module for passport local strategy, we added two routes; one for displaying login page and another for handling the callback url. After "/login" route is called, we request users to enter their email id and password.




If email id and password submitted by the user matches with these values, we return the email id of the user. If no match is found then we return false to indicate that authentication failed.

This is possible with the help of done() function. It is an internal passport js function that takes care of supplying user credentials after user is authenticated successfully. This function attaches the email id to the request object so that it is available on the callback url as "req.user".

It will be available for the dashboard route, where you would set the session for the user and then to another part of your web application.

Importance of passport.authenticate() function


This function is internally used by passport js to make sure that users are logged in before they are going to that url directly. It should be used in such a situation when they must be logged in order to access a protected url of the application. For example, to access dashboard page user must be logged in first.


Setting up middleware to check if a user is already logged in or not


To check if someone is logged in we need to check if req.session.user value is set. Then we need to use this function as middleware on GET route(s) that we want to grant access to only logged in users. The code for middleware is given below.



In the above code, we checked to see if the user is authenticated or not using passport js's built in isAuthenticated() function. If user is authenticated, the request continues as next() function is called. Otherwise, user is redirected to login page.

We want to allow only logged in users to visit the dashboard page, the code for doing so is given below.



In the code above, we have added the isLoggedIn() function that we created earlier to the dashboard route. It will act as a middleware to allow only logged in users to visit the dashboard page.


How serializeUser() and deserializeUser() actually works


After successful authentication, passport attaches user's email id to the req.user object. It is possible due to the existence of serializeUser() and deserializeUser() functions.

Previously, when we configured passport js by setting up the callback function, we passed the email value in done() callback function. This step was necessary, as passport needs to take the email id and store it internally in req.session.passport object which is passport's way of keeping track of things.

For accomplishing this task, serializeUser() function must be defined. The code for this function is provided below.



In the deserializeUser() function, the email id is given as the first parameter which is same email id that was passed in the serializeUser() function. Then this function makes a request to the database to find email id of the user by invoking done() function. After this step, the email id of the user is attached to the req.user object.



Finally, The Application That We Will Build


We will be building a simple web application that will explain how to work with passport local module which is a package provided by passport js itself. We won't be storing user credentials in any database. We are doing this intentionally so that you can focus on the essential concepts related to passport js. But, in real world application, a database must be used.

Note: To follow along with this tutorial, you need to download the project file.

Download Button


Then make sure you have installed node js in your computer. After download is finished extract the downloaded rar file. Open terminal or command prompt in the location where you downloaded the project. Run this command "npm install", then run "npm start", open a web browser and type "http://localhost:8000/login" to run the application.

Overall Project Structure


Passport js Part 1 Overall Project Structure
Overall Project Structure

Discussion on project structure


app.js file: The main gateway to our express js application. Here, we will set all the dependencies, all middlewares required for the application and error handling codes etc.

routes/index.js file: In this file, we are storing all the routes for our application.

views folder: It stores all the dynamic pages for our application. For generating dynamic content for our pages, we are using handlebars as the template engine. For now, it contains two pages i.e, dashboard.hbs and login.hbs.

public folder: This folder stores all the static resource files(i.e, css,js, image files etc) required by the dashboard.hbs and login.hbs pages.

package.json file: It stores various modules that are required for building the application.

Creating The Node Server




Explanation of the app.js file


In app.js, we need to store all the references to third party modules that are used for the application. Then we need to configure them accordingly. One important note I would like to mention here, if we are using express-session module in our application, then we must configure passport middleware just after express-session middleware setup.

Configuring Passport




I already explained how this configuration actually works. If you want to revisit that section, go to the heading entitled "Topics Covered In This Article".


Creating The Login Page




Creating The Dashboard Page





Conclusion


Thank you for going through this article. If you learn something new and exciting, please share this article among others.

No comments:

Post a Comment