Node Express:Passport JWT中间件未被执行

时间:2017-12-12 01:33:50

标签: node.js express passport.js

当我在路线中使用'passport.authenticate('jwt',{session:false})'时,它会返回'未授权'。护照中间件似乎无法正常工作。我不知道有什么不对!在标题中,我使用的是“授权:JWT MY_TOKEN”。

app.js文件

// ...code

const app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
require('./config/passport')(passport); // passport middleware file

app.use('/api/auth', auth); // routes
app.use('/api/lists', lists); // routes  

Passport中间件文件:

const { Strategy, ExtractJwt } = require('passport-jwt');
const User = require('../models/User');
const keys = require('./keys');

module.exports = (passport) => {
    const opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
    opts.secretOrKey = 'MYSECRETKEY';

    // HERE IS EXECUTED! <<<<<<<<

    passport.use(new Strategy(opts, function(jwt_payload, done) {
        // HERE IS NOT BEING EXECUTED! <<<<<<<<

        User.findOne({_id: jwt_payload.id}, function(err, user) {
            if (err) {
                return done(err, false);
            }
            if (user) {
                return done(null, user);
            } else {
                return done(null, false);
            }
        });
    }));
}

登录路线(创建令牌):

router.post('/login', (req, res, next) => {
  const { email, } = req.body;

  User.findOne({ email: email }, { password: 0 }, (errQuery, resUser) => {
    const token = jwt.sign({_id: resUser.id}, 'MYSECRETKEY');

    const responseData = {
      status: true,
      token: `JWT ${token}`
    };

    res.send(responseData);
  });
});

1 个答案:

答案 0 :(得分:2)

问题是这一行:

<?php if (is_home()) { ?>
     <div class="owl-carousel">...</div>
<?php } ?>

因为您正在调用该配置选项,所以您的标题需要如下所示:

opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();