2

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.

Jones Stephen
  • 473
  • 1
  • 5
  • 17
  • Refer this link https://stackoverflow.com/a/45750615/7635845.This is my answer.Hope this helps.If it helps do upvote.Otherwise let me know if you have any doubts. – Syed Ayesha Bebe Aug 24 '17 at 11:36

2 Answers2

7

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

opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
Jones Stephen
  • 473
  • 1
  • 5
  • 17
  • I am doing the same thing and made the change suggested, but still getting unauthorized.here is the link to my code [link](https://stackoverflow.com/questions/46219984/authorization-issue-using-passport-jwt) – cacev000 Sep 15 '17 at 15:36
  • @cacev000, check your jwt_payload `console.log('test',jwt_payload); User.getUserById(jwt_payload.data._id, (err, user) => {`., sometimes your _id is under `jwt_payload.doc._id` – Jones Stephen Feb 14 '18 at 19:38
6

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

Akhil Clement
  • 575
  • 1
  • 7
  • 17