护照令牌未被授权

时间:2019-03-22 12:27:55

标签: node.js express jwt authorization passport.js

const JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/User');
const key = require('./keys').secret;
const mongoose = require('mongoose');

var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = key;

module.exports = (passport) => {
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    console.log(jwt_payload);
    User.findById(jwt_payload.id, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, user);
        } else {
            return done(null, false);

        }
    });
}))
}

我正在使用passport-jwt战略来验证令牌,但这是文件无法正常运行,我什至试图在此处管理有效负载,但这甚至没有记录它

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

令牌策略

 const payload = {
                    id: user.id,
                    username: user.username,
                    name: user.name
                }
                const token = jwt.sign(payload, config.secret, { expiresIn: 36000 });
                return res.json({
                    success: true,
                    token: 'JWT ' + token,
                    user: {
                        id: user.id,
                        name: user.name,
                        username: user.username
                    }
                })

当我在受保护的路由上使用它时,未授权受保护的路由

结果=未经授权

router.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
res.send("Profile");
});

1 个答案:

答案 0 :(得分:0)

身份验证不起作用的原因是,您已使用旧式令牌前缀“ JWT”和现代的JWT(fromAuthHeaderAsBearerToken)提取器作为策略的选项。

您可以执行以下步骤之一来解决此问题:

  1. 将令牌前缀更改为'Bearer ' + token
  2. 更改令牌提取器:

    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");