Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 265
Saurabh Sharma Avatar asked Nov 20 '25 08:11

Saurabh Sharma


1 Answers

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

like image 110
Kasra Karami Avatar answered Nov 23 '25 03:11

Kasra Karami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!