I am new to nodejs. I need to create and authentication using nodejs. Here I found few answers but they also used old version. Here I am using these versions
I used this code to create the passport.js file in my node application.
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const config = require('./db');
const User = require('./models/user');
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secret;
module.exports = (passport)=>{
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findUserbyId({_id: jwt_payload._doc._id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
};
And I used this routes method to create a route with the Authentication.
router.post('/profile',
passport.authenticate('jwt'),{ session: false },
(req, res)=> {
res.json({user:req.user});
});
I used postman to create a token and check the authentication.
I cannot understand the why it wrong. findUserById method is follow
module.exports.findUserbyId = (id, callback)=>{
User.findOne(id, callback);
}
What's the problem in my code? Why it every time gives
unauthorized
in my postman application.