Jones Stephen
Jones Stephen

Reputation: 493

Passport-jwt Unauthorized

I'm New to node js. I'm using passport jwt for authentication. When i tried to authenticate, its always showing "unauthorized".

my passport.js file

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');

module.exports = function(passport){
  let opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, (jwt_payload, done) => {

    User.getUserById(jwt_payload._doc._id, (err, user) => {
      if(err){
        return done(err, false);
      }

      if(user){
        return done(null, user);
      } else {
        return done(null, false);
      }
    });
  }));
}

user model user.js

module.exports.getUserById = function(id, callback){
  User.findById(id, callback);
}

routes

router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
  res.json({user: req.user});
});

When I google it many suggested to change this line in passport.js

User.getUserById(jwt_payload._doc._id, (err, user) => {

I tried with

User.getUserById(jwt_payload._id, (err, user) => {
User.findById(jwt_payload._id, (err, user) => {

still now i'm getting this same error.

Upvotes: 2

Views: 5103

Answers (2)

Akhil Clement
Akhil Clement

Reputation: 685

if you are using opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); as your jwtFromRequest then your Authorization header is like

bearer xxxxx.yyyyy.zzzzz

you can check the BEARER_AUTH_SCHEME specified in the extract_jwt.js located in the passport-jwt/lib folder


if you are using opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt') as your jwtFromRequest then your Authorization header is like

JWT xxxxx.yyyyy.zzzzz

you can check the LEGACY_AUTH_SCHEME specified in the extract_jwt.js located in the passport-jwt/lib folder

Upvotes: 6

Jones Stephen
Jones Stephen

Reputation: 493

I found out the issue, In new passport-jwt updates, we have to use

opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');

Upvotes: 7

Related Questions