Node.js | Authentication Using passport.js

Talha nousher
Webtips
Published in
4 min readSep 8, 2020
Image

In this article, I will share my knowledge of authenticating node.js server using passport.js and also a little stuff about protected routes and handle unauthorized requests.

I am using the following things.

  • Node.js
  • Express.js
  • passport.js
  • JWT

This article just gives you the basic understanding of authenticating users with passport.js and has nothing to relate to schema designing or other concepts using in node server.

The below paragraph is taken from the official website of passport.js

Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

I will try to explain the whole thing in steps so that you guys can easily understand

Step # 1

Create an express application using express-generator to create a project by using the following command in the command prompt.

express [project-name]

then cd into your project folder and open it in your favorite code editor mine is VS code
Run the following command to install dependencies.

npm install

Step # 2

The project is set up and the next thing that we have to do is install passport.js

We have to install a passport and passport-local using the following command at the root of the project directory

npm install passport passport-local --save

passport-local is a passport strategy for authenticating with username and password.

By plugging into the passport this module allow us to authenticate the user with a username and password.

Step # 3

Once passport and passport-local was installed the next step is to require it into your project

The project which we created previously has an app.js file and before using the routes that are using passport you have to require a passport and integrate it.

If you use mongoose then you also have to install passport-local-mongoose and add it to your user schema

You are free to define your User schema in a way you like passport-local-mongoose add a username, hash, and salt field to store the username, hashed password, and salt values within your user schema.

Passport attaches the profile information to req.user and this occurs as a result of the serializeUser() and deserializeUser() functions. Passport.serialize and passport.deserialize are used to set id as a cookie in the user’s browser and to get the id from the cookie when it then used to get user info in a callback.

After initializing the passport the next step is to make the APIs for registration of user or login user.

Step # 4

I am making a separate file for the user route and import in app.js and pass it to app.use after initializing the passport.

The user routes file is looking like this

These two routes ‘/register’ and ‘/login’ are the basic that we discuss in this article. I have made a separate file for callback functions and require them as userHandler and pass it to routes.

First, we discuss the Registration API

The register function in the handler file that is required in user routes and pass to ‘/register’ endpoint looks like this.

User.register function is only available if you add passport-local-mongoose in the user schema and it will simply create a new user in the database or returns an error if the user with a given username already exists.

auth.getData is a function that takes the user data sealed it using Iron generate the JWT token and return the user data

The seal password must be saved somewhere locally usually we keep it in the .env file and not share with anyone ( must add .env file in .gitignore file )

verify.getToken function takes the sealed user and returns the JWT token which we send in the response of API call to be stored in Front end application and use further for accessing other private APIs.

jsonwebtoken is also using a secret key to generate a token this secret key must be stored somewhere locally usually in the .env file.

This is all for user registration API. Run the server using

npm start

Make sure you have connected the database ( local or deployed somewhere ) Hit the following endpoint using postman or CURL

POST http://localhost:3000/users/register

also include username and password as a JSON object in a body and you will get the user data along with the JWT token.

For Login

The login call back in userHandler is written as

Passport. authenticate first param is a strategy that we use, in this case, it is local’

and it returns the user in a callback which is used by our auth.getData function to generate a token and return as a response to Front end application.

I have tried to keep the article as simple as I can but if you guys still have some confusion or questions please refer to the following git repository

Github Link

If you find any error please report.

Thanks!

--

--

Talha nousher
Webtips
Writer for

Bachelors in Computer science. JavaScript developer, Working as MERN stack developer. Interested in writing tech articles related to node.js and react.