【问题标题】:NodeJS jwtStrategy requires a function to retrieve jwt from requests errorNodeJS jwtStrategy 需要一个函数来从请求错误中检索 jwt
【发布时间】:2016-07-31 17:37:00
【问题描述】:

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

passport.use(new JwtStrategy(opts, function(jwt_payload, done)

这是我运行节点“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

解决办法是什么?

【问题讨论】:

  • 感谢这篇文章也做了这个教程,也得到了这个错误

标签: node.js passport.js


【解决方案1】:

我认为您使用的是 'passport-jwt' 2.0.0,它从本教程使用的 v1.x.x 中添加了一些重大更改。在 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
        }
    });
}));

【讨论】:

  • 对于面临ExtractJwt.fromAuthHeader is not a function 错误的任何人,从 passport-jwt 2.0 到 3.0 都有重大更改!您应该使用其他一些提取器,例如 fromAuthHeaderAsBearerToken。检查npmjs.com/package/passport-jwt#included-extractors 提取器列表。
  • @IshanThilinaSomasiri 你是救生员。模组,这个答案的编辑队列似乎已满。您能否分析编辑并将上述评论添加到此答案中?
【解决方案2】:

来自official documentation,当使用 JWT 从 2.x 迁移到 3.x 时,您应该使用:

ExtractJwt.fromAuthHeaderWithScheme('jwt')

而不是旧的:

ExtractJwt.fromAuthHeader()

【讨论】:

  • 我之前使用的是经过验证的解决方案,但是当我开始一个新项目时,我没有意识到我使用的是 3.x,而这个解决方案解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 2018-01-13
  • 2021-12-29
  • 2022-06-28
  • 2022-12-03
  • 2021-07-30
  • 2020-06-29
  • 2017-12-16
  • 2020-02-21
相关资源
最近更新 更多