您正在使用 passportjs 和 passport-jwt 。再看一下文档,该策略如何从请求中“提取” JWT 令牌(尤其是随附的“有效负载”)。 Passport-JWT Documentation
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const opts = {
jwtFromRequest : ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey : 'secret',
issuer : 'accounts.examplesoft.com',
audience : 'yoursite.net'
}
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
// jwt_payload is the payload that you earlier included
// in the jwt token, when you created the jwt token.
// Here you can verify the request,
// For example, check database if user exists.
User.findOne({id: jwt_payload.sub}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));
有了这个,您通常不需要额外的“checkAuth”功能。像这样使用它:
app.use(passport.authenticate('JWT', {session: false}));
// OR
app.post('/protected', passport.authenticate('JWT', {session: false}), (req, res) => {
// this will only fire when authentication was successfull
// req.user will hold whatever you return in the callback from
// the strategy function.
});