NodeJS : JWT Token With Passport Authentication

Posted By : Shashwat Gupta | 31-May-2018

JWT with Passport authentication in Node Js

Introduction :-

 

All web app and mobile application have authentication . so, Passport is a Node.js Lib that provides serval authentication strategies that are very simple to implement.Passport Lib. stores the user object in session by default

JSON Tokens is an authentication strategies that work with cookies  to identify the logged in user, instead of storing the user in a session 

 

Today , we will use two modules together ( JWT and Passport.js) for authentication on an express based backend. 

 Passport Node js Lib. is now provide us an option to store the user object in request instead of the session.

Firstly , install athe dependencies.

npm install --save passport passport-local passport-jwt jsonwebtoken

every thing should be fine here :

  • When any user get logged inside our application, then backend server will create token and returns that token in response
  • The client will save that token in localStorage and sends token back in every request that needs authentication
  • All requests will have authenticated  in middleware that will check  token and allows the request to perfome if the token is correct

 

Login:

 

var _passport = require('passport’);
var _LocalStrategy = require('passport-local').Strategy;
_passport.use(new _LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    }, 
    function (emailId, pass, callback) {
         
        return User.findOne({email, password})
           .then(user => {
               if (!user) {
                   return callback(null, false, {message: 'Incorrect email or password.'});
               }
               return callback(null, user, {message: 'Logged In Successfully'});
          })
          .catch(err => callback(err));
    }
));

 in app.js.

//app.js
var express = require('express');
require('./passport');

var app = express();
...
var auth = require('./routes/auth');
app.use('/auth', auth);
//routes/auth.js
const express = require('express');
const router  = express.Router();
const jwt = require('jsonwebtoken');
const passport = require("passport”);
/* POST login. */
router.post('/login', function (req, res, next) {
    passport.authenticate('local', {session: false}, (error, user, info) => {
        if (err || !user) {
            return res.status(400).json({
                message: 'Something is not right',
                user   : user });
           
        }
       req.login(user, {session: false}, (error) => {
           if (error) {
               res.send(err);
           }
           var token = _jwt.sign(user, 'your_jwt_secret');
           return res.json({user, token});
        });
    })(req, res);
});

 

Protected requests

 

 

var _passportJWT = require("passport-jwt");
var _JWTStrategy   = passportJWT.Strategy;
var _ExtractJWT = passportJWT.ExtractJwt;

_passport.use(new _JWTStrategy({
        jwtFromRequest: _ExtractJWT.fromAuthHeaderAsBearerToken(),
        secretOrKey   : 'your_jwt_secret'
    },
    function (jwtPayload, callback) {

        
        return User.findOneById(jwtPayload.id)
            .then(user => {
                return callback(null, user);
            })
            .catch(err => {
                return cllback(err);
            });
    }
));

 

//routes/user.js
var express = require('express');
var router = express.Router();

 
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

 
router.get('/profile', function(req, res, next) {
    res.send(req.user);
});

module.exports = router;

 

//app.js
var express = require('express');
...
require('./passport');

var app = express();
var auth = require('./routes/auth');
var user = require('./routes/user');
app.use('/auth', auth);
app.use('/user', passport.authenticate('jwt', {session: false}), user);

Done

About Author

Author Image
Shashwat Gupta

Shashwat is a bright Mean Stack Developer . He has good experience in development of complex UI's of web application and hybrid mobile applications.

Request for Proposal

Name is required

Comment is required

Sending message..