JWT Token Based Authentication using Passport in Node.js

Posted at: April 10, 2020 6:45 PM

This is a very important lesson. In this lesson we will learn token-based authentication using a passport in the Node.js.

JSON Web Token (JWT)

JSON Web Token (JWT) authentication is a very popular method to present time. JWT is token-based authentication means send token in every request from client to server and verify token on the server then return a response to the client. No need sessions or cookies in token-based authentication. For more details go to JSON Web Token.

Before starting this lesson needs to learn previous lesson User Registration in Angular 8

Install JSON Web Token (JWT) in node.js application.

Passport.js

Passport is authentication middleware for Node.js. Passports use for authenticate requests, which it does through different type of strategies. A set of strategies support authentication using a username and password, Facebook, Twitter, and more. In this tutorial we will learn use of LocalStrategy with username and password. For details go to Passport.js Documentation

Install passport in your node.js application

For LocalStrategy install passport-local

Install passport-jwt for extracting the JWT from the request.

auth-model.js

For database query we have created two methods findOne for user login and findById for request authentication.

Full code of auth-model.js

Configure Authentication Strategies

Before asking passport to authenticate a request, the strategy (or strategies) used by an application must be configured. Create a file passport-config.js in your application root folder.

Require following modules in passport-config.js

var passport = require('passport'); for enable passport features.

var LocalStrategy = require('passport-local').Strategy; for local strategy.

var bcrypt = require('bcrypt'); for match encrypted database password with client password.

var authModel = require('./models/auth-model'); for database query execution.

var JwtStrategy = require('passport-jwt').Strategy; for request authentication.

var ExtractJwt = require('passport-jwt').ExtractJwt; for extract JWT token.

options is an object to control how the token is extracted from the request or verified.

passport-config.js

Strategies, and their configuration, are supplied via the use() function.

LocalStrategy Configuration

Use JwtStrategy for Request authentication.

Complete code of passport-config.js

auth.js

Create login route in routes/auth.js and generate jwt token using jwt.sign() method and send token as response to the client after login success.

In this token I have claimed in payload

  • Set payload data username and email. You can set any data in the payload like as xyz: abc
  • Use user id as token subject i.e. subject: `${user.id}`
  • This token will be expire in 1 hour i.e. expiresIn: 3600
  • Generate token const token = jwt.sign(payload, 'secret123', options);

Note: Don't store sensitive data in token.

You can use any secretOrPrivateKey according token algorithm. In this token we have used secret123 of secretKey.

Disable Sessions

After successful authentication, Passport will establish a persistent login session. The session will be useful when users access the web application via the browser. But the session is not necessary in the API because api send token with each request and verify token on the server and send response to the client. In the case, we can disable the session by setting the session option to false. i.e. {session: false}

Complete code of routes/auth.js

Authenticate Requests

Use passport.authenticate() specifying 'JWT' as the strategy.

Create product.js file in the routes folder for check jwt token authentication. This route file we will use further.

Authenticate requests using two types.
1. Authenticate Specific Request

If you want to authenticate a particular request in the given route then call passport.authenticate() in specific request.

Complete code of routes/product.js

2. Authenticate Specific Route

If you want to authenticate all requests in the given route then call passport.authenticate() in the route there defined. For example

  • http://localhost:3000/product
  • http://localhost:3000/product/xyz
  • http://localhost:3000/product/xyz/abc

Complete code of routes/product.js

I have used second method "Authenticate Specific Route" in this tutorial.

app.js

Require product route in app.js

Complete code of app.js

Conclusion

In this lesson we have learned jwt token based authentication in the node.js using a passport. We learnt some features like as generate jwt token, extract jwt token, authenticate requests, match encrypted password, etc. Next lesson we will use this login api in Angular 8 for logging.

This lesson also available on YouTube
local authentication using passport in node.js jwt token based authentication in node js node js token authentication jwt.verify example jwt authentication node js jwt token authentication web api jwt token authentication jwt token based authentication in web api

Please leave comments

1 Comments