我一直在尝试使用 Passport 和 Passport -jwt 来测试 protected 路线。
我已经做到了当用户尝试登录并在 Postman 中测试它时生成 token 的程度。
我创建了一条路线,并作为参数 Passport.authenticate 使用 jwt 策略传入,但到处都出现错误。
在我的主 server.js 中,我需要 Passport :
passport = require('passport');
app.use(passport.initialize());
// passport config
require('./config/passport')(passport);
在我的 Passport 配置文件中,我有这个:
const jwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model('users')
const keys = require('../config/keys');
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;
module.export = passport => {
passport.use(
new jwtStrategy(opts, (jwt_payload, done) => {
console.log(jwt_payload);
}));
};
我的路线是这样的:
// @route get to /users/current
// @desc: return the current user (who the jwt token belongs to)
// @access: should be public
router.get('/current',
passport.authenticate('jwt', { session: false }),
(req, res) => {
res.json({msg: "Success"})
}
);
我似乎无法通过的第一个错误是在控制台中:
require('./config/passport')(passport);
^
TypeError: require(...) is not a function
在 postman 中,当我尝试转到/users/current 并传入已确认的不记名 token 时,我得到以下信息:
错误:未知的身份验证策略“jwt”
尝试时
最佳答案
在 Passport 配置文件中
你有拼写错误 module.export
实际上是 module.exports
这就是为什么在 require 之后它不会将其识别为函数
关于node.js - JWT token 发行和 Passport w/node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428485/