JWT令牌问题和护照w /节点js

时间:2018-05-19 18:53:07

标签: node.js passport.js

我一直在尝试使用护照和护照-jwt来测试受保护的路线。

当用户尝试登录并在Postman中对其进行测试时,我已经达到了生成令牌的程度。

我已经创建了一个路由,并以jwt策略作为参数传递了passport.authenticate,并且在整个地方都出现了错误。

在我的主server.js中,我需要护照:

passport = require('passport');

app.use(passport.initialize());

// passport config
require('./config/passport')(passport);

我的文件夹结构如下: enter image description here

在我的护照配置文件中,我有:

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

在邮递员中,当我尝试转到/ users / current并传递确认的持票人令牌时,我明白了:

错误:未知的身份验证策略“jwt”在尝试时

3 个答案:

答案 0 :(得分:1)

护照配置文件中的

你有错误df1.loc[column,:] = np.nan 其实为module.export 这就是为什么之后需要它不会将其作为函数重新识别

答案 1 :(得分:0)

将module.export更改为

module.exports = passport => {
    passport.use(
        new jwtStrategy(opts, (jwt_payload, done) => {
        console.log(jwt_payload);
    }));
};

答案 2 :(得分:0)

其module.exports而不是module.export。

可以为module.exports属性分配一个新值(例如函数或对象)。

module.exports = class Square {
constructor(width) {
this.width = width;
}
area() {
return this.width ** 2;
}
};

nodejs modules documentation reference