0

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 enter image description here

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. enter image description here

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.

jps
  • 20,041
  • 15
  • 75
  • 79
dhananjana
  • 53
  • 1
  • 12
  • did you read [this](https://stackoverflow.com/questions/45858758/passport-jwt-unauthorized)? Try to replace the string "JWT" in your Authorization-Header with "Bearer" (and also a blank between "Bearer" and the token. – jps Jun 28 '18 at 14:03
  • sorry sir I tried that but now I am getting "Cannot POST /users/profile" error. when I changed that and after changing my post method to get method. – dhananjana Jun 28 '18 at 14:30

0 Answers0