如何使用passport-jwt验证路线? [英] How to authenticate a route with passport-jwt?
问题描述
我正在使用passport-jwt
,我的策略设置如下:
I'm using passport-jwt
and my strategy is setup like:
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
路由时,我能够生成令牌:
So when I POST to a /login
route, I'm able to generate a token:
var payload = { id: user.id }
var token = jwt.sign(payload, jwtOptions.secretOrKey)
res.json({ message: "ok", token: token })
但是当我尝试使用需要令牌的路线时:
But then when I try to have a route that requires a 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
.我在做什么错了?
it continually returns a 401
. What am I doing wrong?
推荐答案
您的授权标头格式错误.根据 jwt-strategy文档
Your authorization header is incorrectly formatted. Per the jwt-strategy docs
fromAuthHeaderAsBearerToken()
创建一个新的提取器,该提取器使用方案"bearer"在授权标头中查找JWT
fromAuthHeaderAsBearerToken()
creates a new extractor that looks for the JWT in the authorization header with the scheme 'bearer'
因此标题应该为Authorization: Bearer [token]
这篇关于如何使用passport-jwt验证路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!