NodeJS jwtStrategy需要一个函数来从请求错误中检索jwt

NoN*_*me2 17 node.js passport.js

我从https://devdactic.com/restful-api-user-authentication-1/学习了教程.但是这部分我得到了错误

passport.use(new JwtStrategy(opts, function(jwt_payload, done)
Run Code Online (Sandbox Code Playgroud)

运行节点"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
Run Code Online (Sandbox Code Playgroud)

解决办法是什么?

has*_*sin 40

我认为你正在使用'passport-jwt'2.0.0,它增加了本教程使用的v1.xx的一些重大变化.在opts你需要传递另一个选项jwtFromRequest告诉它在哪里寻找jwt有效载荷.

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
        }
    });
}));
Run Code Online (Sandbox Code Playgroud)

  • 对于任何面对```ExtractJwt.fromAuthHeader不是函数```错误的人来说,从passport-jwt 2.0到3.0都有重大变化!您应该使用其他一些提取器,例如**fromAuthHeaderAsBearerToken**.检查https://www.npmjs.com/package/passport-jwt#included-extractors提取器列表. (15认同)

小智 25

官方文档中,当使用JWT从2.x迁移到3.x时,您应该使用:

ExtractJwt.fromAuthHeaderWithScheme('jwt')
Run Code Online (Sandbox Code Playgroud)

而不是旧的:

ExtractJwt.fromAuthHeader()
Run Code Online (Sandbox Code Playgroud)