JWT Token Based Authentication using Passport in Node.js
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 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.
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.
Strategies, and their configuration, are supplied via the use() function.
Use JwtStrategy for Request authentication.
Complete code of passport-config.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
- Use user id as token subject i.e.
- This token will be expire in 1 hour i.e.
- 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.
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.
Complete code of routes/auth.js
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
Complete code of routes/product.js
I have used second method "Authenticate Specific Route" in this tutorial.
Require product route in app.js
Complete code of app.js
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
More Posts - MEAN Stack
- MEAN Stack with MySQL
- Integrate Angular 8/9 with Node.js in MEAN Stack
- Routing, Lazy Loading Modules and Multiple Layouts in Angular 8/9
- User Registration in Angular 8/9 in MEAN Stack
- JWT Token Based Authentication using Passport in Node.js
- Angular 8/9 JWT Authentication with Example in MEAN Stack
- MEAN Stack Tutorial with CRUD Operations
- Server Side Pagination in MEAN Stack (MySQL, ExpressJS, Angular, NodeJS)
- Angular 9 Drag and Drop File Upload with Progress Bar using Node js API