Authenticate endpoints using a JSON web token (passport-jwt)

Shashivardhan M
2 min readMar 18, 2021

This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions

Add passport-jwt package in your node project

npm i passport-jwt

Require the package in your project app.js file

const passport = require(‘passport’);

const {ExtractJwt} = require(‘passport-jwt’)

Configure the options for JWT authentication

const jwtOption = {}

/******configuration which reads the JWT from the HTTP Authorization header with the scheme ‘bearer’****/

jwtOption.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()

/******“secretOrKey” is a string or buffer containing the secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token’s signature******/

jwtOption.secretOrKey = “TOKEN_SECRET”

Now, Construct the JWT authentication strategy as below

const jwtStrategyConfig = new JwtStrategy(jwtOption, (jwtPayLoad, done)=> {

/**

* jwtPayLoad is an object literal containing the decoded JWT payload.

* done is a passport error first callback accepting arguments done(error, user, info)

**/

collectionName.findOne({phone_number: jwtPayLoad.id},(errorInFindingPhoneNumber, foundPhoneNumber) => {

if (errorInFindingPhoneNumber) return done(errorInFindingPhoneNumber, false);

if (foundPhoneNumber) done(null, foundPhoneNumber);

else done(null, false);

});

});

And finally, add strategy to passport in the “app.js”

passport.use(jwtStrategyConfig)

Now create a new file in the service folder “jwtauthenticationservice.js

jwtauthenticationservice.js

/** Requires */

const passport = require(‘passport’);

/*** Middleware to authenticate the API request using JWT token**/

module.exports = {

initialize: function () {return passport.initialize();},

authenticate: function (req, res, next) {return passport.authenticate(“jwt”, {session: false}, (errorInAuthenticatingJWTToken, foundAuthenticatedUser, authenticatedInformation) => {

if (errorInAuthenticatingJWTToken) {return next(errorInAuthenticatingJWTToken);}

if (!foundAuthenticatedUser) {return res.json(“UNAUTHORIZED_USER”);}

// Forward user information to the next middleware

req.user = foundAuthenticatedUser;

next();

})(req, res, next);

}};

After setting up the above code

Require the “jwtauthenticationservice.js” in the routes file

Example:-

In the “index.js” router file

const express = require(‘express’);

const router = express.Router();

const jwtAPIAuthentication = require(‘../services/jwtauthenticationservice.js’)

router.post(‘/getuserdetails’, jwtAPIAuthentication.authenticate, (req, res) => {res.json(“SUCCESS”);});

--

--