JWT Authentication in Node JS With MEAN Stack Application - CodAffection
[the_ad_placement id="before-content"]

JWT Authentication in Node JS With MEAN Stack Application

JWT Authentication with Node.js

This article is a continuation to the previous MEAN Stack user registration project. Here we extend the same project by implementing JWT Authentication in Node JS using NPM Packages jsonwebtoken and passport.js.

Please watch this 10min tutorial for understanding JWT Authentication in depth:

GitHub link up-to this article : https://goo.gl/f1Q6cT

So far we have discussed following related topics in MEAN Stack:

  1. CRUD Operation – Insert Update View and Delete.
  2. User Registration
    Node JS Back End.
    Angular 6 Front End.
  3. JWT User Authentication
    Node JS Back End.( this article)

Install Required NPM Packages

In addition to the existing packages,  let’s install few more packages – jsonwebtoken, passport, passport-local and lodash.

npm i --save jsonwebtoken passport passport-local lodash

Configure Passport for Local Authentication

Passport can act as an authentication middleware in NodeJS Application. It makes the process more easier. It has various strategy for authentication.
Eg : local strategy(using username and password) , strategy using social accounts like facebook, twitter, gmail etc.

In this project we’ll use email and password as user credentials for authentication.Lets check how to configure passport local strategy with passportConfig.js file.

use function from passport will configure the middleware. Inside the function, an object of localStrategy is a passed with one option and a call back function.

For option, we mention usernameField = email. because by default local strategy uses username and password but for this application we will use email instead of username.

Inside the callback function, we have defined user authentication criteria for both success and failure with the help of findOne function from mongoose. this callback function will get executed when actual authenticate function from passport is called.

Now we have to add following lines in Node JS route file – app.js.

Add Post Route For User Authentication

To implement user authentication, we’ll add a route function – authenticate  inside user.controller.js.

As soon as we call the authenticate function from passport, the middleware function that we just created will be executed after that the callback function inside this authenticate function will called. parameter for this function passed though done from middleware callback function. If the authentication is successful jwt token is generated using generateJwt function from user model.

Now we have to define function generateJwt  in user.model.js file.

In-order to generate the jwt token we just need to call sign function from jsonwebtoken. 

first parameter is the payload for the token. inside that we will provide various claims or information about the user. here we stored user id(_id) from mongoDB user record. we can pass as much as details we want, but don’t store unwanted information inside payload, it will make the token bigger in size. This payload is stored in jwt as result of encoding not encryption. so NEVER store security information like password in this payload.

second parameter is the secret code for the encryption of signature part. Last parameter is the token expiration time.
both of these secret code and expiration time is stored in config.json file as follows.

Update index.router.js for this new authenticate route as follows.

Now we can make a post request – /api/authenticate with email and password. If there is a user with given credential then jwt token can be received at client side. Normally we save this token in browser local storage because we need the token in order to access private routes from Node JS API.

Secure Private Routes in Node JS Using jsonwebtoken

In-order to access private routes, the request must have the valid jwt token. In server side node js application, jsonwebtoken will verify the attached token. If it is valid then only the secured private route get consumed.

So let’s check how to verify jwt. for that I’ll add new file jwtHelper.js  as follows.

If you make request to consume private you should add jwt in header as follows.

AUTHORIZATION : bearer [jwt]

Inside verifyJwtToken  function, we split Authorization header by space and stores the jwt inside token variable. If there is a token in request header then we call verify function from jsonwebtoken. Inside the function callback we ‘ll have the decoded payload. that means user id(_id) stored during token generation can be retrieved here. we will save the payload in request so that private routes can use these values.

User Profile

Here I’ll add new route UserProfile then we will make route as private. Define router function userProfile in user.controller.js.

From this function, we return details of the current user. user id decoded during token verification is used here – req._id. In-order to pick few properties from user object we use lodash function pick.

Now let’s make this route as private.For that you can do the following in index.router.js.

Done. In the next article we will add client side Angular 6 login and logout component to this MEAN Stack Project.

Complete Video Tutorial

7 thoughts on “JWT Authentication in Node JS With MEAN Stack Application”

  1. I am getting this error when i try to post in “postman” – “expiresIn” should be a number of seconds or string representing a timespan”.
    Kindly help.

  2. is it possibe to generate tokens for users and clients which are in different collections using passport,because by default passport checks only for user collection,how to achieve tokens for two different collection

Leave a Comment

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

Scroll to Top
Share via
Copy link
Powered by Social Snap