如何在同一个应用程序中调用多个passport-jwt策略

时间:2019-02-25 16:37:02

标签: node.js express passport.js

我能够区分两条路线, 验证第一条路线(学生)。当我呼叫第二条要验证的路线(老师)时,将返回一个空的JSON文件。

在users.js中,“ passportStudent.authenticate”可以正常工作并返回具有预期用户信息的JSON文件,但是我不确定为什么“ passportTeacher.authenticate”会返回空的JSON文件。

这是我的代码:

users.js:

const passportStudent = require('passport');
const passportTeacher = require('passport');

/*Some code here*/

router.get('/profile/student', passportStudent.authenticate('student', {session: false}), (req, res, next) =>{
    res.json({user : req.user});
});

router.get('/profile/teacher', passportTeacher.authenticate('teacher', {session: false}), (req, res, next) =>{
    res.json({teacher : req.teacher});
});

passport.js:

    const JwtStrategy = require('passport-jwt').Strategy;
    const ExtractJwt = require('passport-jwt').ExtractJwt;
    const User = require('../models/user');
    const Teacher = require('../models/teacher');
    const config = require('../config/database');

    module.exports = function(passport){
        let opts = {};
        opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
        opts.secretOrKey = config.secret;
        passport.use('student', new JwtStrategy(opts, (jwt_payload, done)  => {
            console.log(jwt_payload);
            User.getUserById(jwt_payload.data._id, (err, user) => {
                if(err){
                    return done(err, false);
                }
                if(user){
                    return done(null, user);
                }
                else{
                    return done(null, false);
                }
            });
        }));

        passport.use('teacher', new JwtStrategy(opts, (jwt_payload2, done)  => {
            console.log(jwt_payload2);
            Teacher.getTeacherById(jwt_payload2.data._id, (err, teacher) => {
                if(err){
                    return done(err, false);
                }
                if(teacher){
                    return done(null, teacher);
                }
                else{
                    return done(null, false);
                }
            });
        }));
    }

护照的app.js代码:

const passportStudent = require('passport');
const passportTeacher = require('passport');

/*Some code here*/

app.use(passportStudent.initialize());
app.use(passportStudent.session());

app.use(passportTeacher.initialize());
app.use(passportTeacher.session());

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

如何在所需的路由上进行身份验证?还是应该为学生选择本地策略,为老师选择jwt?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在两种情况下,护照都将已签名的用户信息存储在req.user中。

因此您需要将教师路由器更新为

router.get('/profile/teacher', passportTeacher.authenticate('teacher', {session: false}), (req, res, next) =>{
    res.json({teacher : req.user});
});

我在这里改变

res.json({teacher : req.teacher});

收件人

res.json({teacher : req.user});