Search code examples
node.jstokenpassport.js

How to decode token after login using passport-jwt


I am encoding token with the loggedin user's id with passport-jwt as below:

var JwtStrategy   =require('passport-jwt').Strategy;
ExtractJwt = require('passport-jwt').ExtractJwt;
var User          =require('../app/models/usermodel');
var config        =require('../config/database');

module.exports=function(passport){
    var opts = {}; 
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.id}, function(err, user) {
          if (err) {
              return done(err, false);
          }
          if (user) {
              done(null, user);
          } else {
              done(null, false);
          }
      });
  }));
};

and login route API:

apiRoutes.put('/login', function(req, res, next){
  User.findOne({email:req.body.email}, function(err, user){
    bcrypt.compare(req.body.password, user.password, function(err, result){
       if(result){
        var token=jwt.encode(user, config.secret);
        return res.json({token:token}); 
      }else{
        return res.json("Incorrect Email and Password")
      }
    })
  })
});

Now I want to get loggedin user's information in dashboard page. For which I am trying to decoding token and trying to get all info of user by adding a authentication in dashboard API route as below:

apiRoutes.get('/dashboard', passport.authenticate('jwt', { session: false}), function(req, res) {
  console.log('User info: ' + req.user._id + '.');
  });

This above code I found in a tutorial to decode token. So, when I hit this /api/dashboard url its showing an error in browser console.

GET http://localhost:3000/api/dashboard 401 (Unauthorized)

I don't know how to decode token and fetch user info. Please help me to solve this issue.

Help appreciated. Thanks


Solution

  • pass token to jwt-decode like this

    install jwt-decode:

    npm i jwt-decode
    

    and you can use it very easy:

    import * as jwtDecode from 'jwt-decode';
    
    const payload = jwtDecode(token);
    

    for example i used this in nestjs middleware:

    import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
    import { Request, Response } from 'express';
    import { UserType } from 'src/users/enums/user.enum';
    import * as jwtDecode from 'jwt-decode';
    
    @Injectable()
    export class ErrorIfNotUser implements NestMiddleware {
      use(req: Request, res: Response, next: Function) {
        const token = req.headers.authorization.slice(7);
        const payload = jwtDecode(token);
    
        if (payload.type !== UserType.USER) {
          throw new UnauthorizedException(
            'sorry! just type user access to this route',
          );
        }
    
        next();
      }
    }
    

    jwt-decode in npm: https://www.npmjs.com/package/jwt-decode