【发布时间】:2018-05-19 08:25:16
【问题描述】:
我正在使用passport-jwt,我的策略设置如下:
let jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
jwtOptions.secretOrKey = process.env.SECRET
var strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
console.log('payload received', jwt_payload);
// usually this would be a database call:
var user = users[_.findIndex(users, { id: jwt_payload.id })];
if (user) {
next(null, user);
} else {
next(null, false);
}
})
passport.use(strategy)
所以当我发布到/login 路由时,我能够生成一个令牌:
var payload = { id: user.id }
var token = jwt.sign(payload, jwtOptions.secretOrKey)
res.json({ message: "ok", token: token })
但是当我尝试使用需要令牌的路线时:
app.get("/secret", passport.authenticate('jwt', { session: false }), (req, res) => {
res.json("Success! You can not see this without a token");
})
我的标题有Authorization: JWT [token]
它不断返回401。我做错了什么?
【问题讨论】:
-
你不在这里展示它,你有没有用你的 JwtStrategy 实例调用
passport.use(strategy)? -
另外,展示您如何格式化您在
GET /secret请求中发送的标头 -
@Paul - 已更新。我正在使用
passport.use(strategy)和标题
标签: node.js express jwt passport.js