使用带节点/表达式的护照获取jwt的有效载荷

时间:2018-10-25 13:31:22

标签: node.js express jwt passport.js

将jwt与护照一起使用。如何获取路由/secretonlyfor2中令牌的有效载荷?还是检查有效令牌所有者是否被允许(例如删除某些数据)的标准方法是什么?

const opts = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.JWT_ENCRYPTION
}

const strategy = new JwtStrategy(opts, (payload, next) => {
    User.forge({id:payload.id}).fetch().then(result => {
        next(null, result);
    });
});


app.post('/getToken', (req, res) => {
    User.forge({email: req.body.email}).fetch().then(result => {       
        result.authenticate(req.body.password).then(user => {
            const payload = {id: user.id, email:user.email};
            const token = jwt.sign(payload,process.env.JWT_ENCRYPTION, {expiresIn: '60s'});
            res.send(token);
        }).catch(err => {
            return res.sendStatus(401);
        });
    });
});


app.get('/secretonlyfor2', passport.authenticate('jwt', {session: false}),(req, res) => { 
    //Want to do something like this
    if (id == 2) {
        res.send('yes');
    } else{
        res.send("no");
    }
});

0 个答案:

没有答案