Reputation: 1422
I learned tutorial from https://devdactic.com/restful-api-user-authentication-1/. But I got error on this part
passport.use(new JwtStrategy(opts, function(jwt_payload, done)
Here is the error when I run node "server.js"
/home/chibi/Documents/connect/project/node_modules/passport-jwt/lib/strategy.js:39
throw new TypeError('JwtStrategy requires a function to retrieve jwt f
^
TypeError: JwtStrategy requires a function to retrieve jwt from requests (see option jwtFromRequest)
at new JwtStrategy (/home/chibi/Documents/connect/project/node_modules/passport-jwt/lib/strategy.js:39:15)
at module.exports (/home/chibi/Documents/connect/project/config/passport.js:10:16)
at Object.<anonymous> (/home/chibi/Documents/connect/project/server.js:30:29)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
What is the solution?
Upvotes: 18
Views: 21768
Reputation: 329
From the official documentation, when migrating from 2.x to 3.x using JWT you should use:
ExtractJwt.fromAuthHeaderWithScheme('jwt')
instead of the old one:
ExtractJwt.fromAuthHeader()
Upvotes: 29
Reputation: 17508
I think you are using 'passport-jwt' 2.0.0 which has added some breaking changes from v1.x.x used by the tutorial. In the opts
you need to pass another option jwtFromRequest
to tell it where to look for jwt payload.
var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
// or you could create a new account
}
});
}));
Upvotes: 41