vikvincer
vikvincer

Reputation: 649

passport-jwt token cannot Authorized

I cant authorize users, I am trying to console log jwt_payload but I cannot see results. I tried to console log jwt_payload, but I cannot see any logs.

passport.js

`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.fromAuthHeader();
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts,(jwt_payload, done) => {
        console.log(jwt_payload);
        User.getUserById(jwt_payload.sub,(err,user)=> {
            if(err){
                return done(err,false);
            }
            if(user){
                return done(null,user);
            }else {
                return done(null,false)
            }

        });
    }));
}` 

//user.js

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

Thanks in advance.

Upvotes: 1

Views: 551

Answers (2)

Sujeewa K. Abeysinghe
Sujeewa K. Abeysinghe

Reputation: 347

if you are using,

ExtractJwt.fromAuthHeaderAsBearerToken();

send Authorization header with Bearer + your genarated token instead JWT + your genarated token

Upvotes: 0

Moksedul Hoque Uzzol
Moksedul Hoque Uzzol

Reputation: 51

Make a request to protected route in your case profile to see jwt_payload output. If you set up other things correctly it should console log something like this { '$__': { strictMode: true, selected: {}, getters: {}, _id: '59761655e1d793141048e7fc', wasPopulated: false, activePaths: { paths: [Object], states: [Object], stateNames: [Object] }, pathsToScopes: {}, emitter: { domain: null, _events: {}, _eventsCount: 0, _maxListeners: 0 } }, isNew: false, _doc: { __v: 0, password: '$2a$10$Ek/lrNKHQcRSuQX1H5c2VONOp5InudCI7KeAHkCw96EDkBcY9FEau', username: 'uzzol', _id: '59761655e1d793141048e7fc' }, '$init': true, iat: 1500966142 }

I can't see your getUserById method but i am pretty sure you will get an error because jwt_payload.sub should be undefined here (don't ask me why).You can use User.findOne({id:jwt_payload.sub},callback) to find a user. But if you want to get a user by mongoose findById method then see what you get from jwt_payload. Now you see the user _id is not under jwt_payload.sub but under jwt_payload._doc._id. so your code should be something like this User.findById({_id:jwt_payload._doc._id},callback);

please check my git repository for a working version: https://github.com/uzzol101/auth_app/tree/master

Upvotes: 1

Related Questions