Passport JWT身份验证提取令牌

时间:2018-08-15 22:07:59

标签: node.js express jwt jwt-simple

我正在使用express&jwt-simple作为中间件api处理登录/注册和认证请求。我试图创建一个.well-known端点,以便其他api可以基于令牌发送来对请求进行身份验证。

这是我的策略:

module.exports = function() {
    const opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
    opts.secretOrKey = securityConfig.jwtSecret;
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        // User.where('id', jwt_payload.id).fetch({withRelated: 'roles'})
        console.log('jwt_payload', jwt_payload)
            User.where('id', jwt_payload.id).fetch()
            .then(user => user ? done(null, user) : done(null, false))
            .catch(err => done(err, false));
    }));
};

这是我的登录路线:

router.post('/login', function(req, res) {
    const {username, password} = req.body;
    Promise.coroutine(function* () {
        const user = yield User.where('username', username).fetch();

    if(user) {
        const isValidPassword = yield user.validPassword(password);
        if (isValidPassword) {
            let expires = (Date.now() / 1000) + 60 * 30
            let nbf = Date.now() / 1000
            const validatedUser = user.omit('password');

            // TODO: Verify that the encoding is legit..
            // const token = jwt.encode(user.omit('password'), securityConfig.jwtSecret);
            const token = jwt.encode({ nbf: nbf, exp: expires, id: validatedUser.id, orgId: validatedUser.orgId }, securityConfig.jwtSecret)
            res.json({success: true, token: `JWT ${token}`, expires_in: expires});
        } else {
            res.status(401);
            res.json({success: false, msg: 'Authentication failed'});
        }
    } else {
        res.status(401);
        res.json({success: false, msg: 'Authentication failed'});
    }
    })().catch(err => console.log(err));
});

这是我众所周知的路线:

router.get('/.well-known', jwtAuth, function(req, res) {
    // TODO: look over res.req.user. Don't seem to be the way to get those parameters.
    // We dont take those parameters from the decrypted JWT, we seem to grab it from the user in DB.
    const { id, orgId } = res.req.user.attributes;
    console.log("DEBUG: userId", id)
    console.log("DEBUG: USER", res.req.user)
    res.json({
        success: true,
        userId: id,
        orgId
    });
});

这是我的jwtAuth()函数:

const passport = require('passport');
module.exports = passport.authenticate('jwt', { session: false });

我实际上如何在route函数中获取令牌并对其进行解密?现在所做的所有工作就是对它进行身份验证(如果为true),但是我需要能够解密令牌以发回存储的值。我不确定res.req.user.attributes来自什么,这是令牌吗?

1 个答案:

答案 0 :(得分:2)

看看passport-jwt并在passport-config(或任何初始化护照的地方)中设置JWT策略:

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;

const jwtAuth = (payload, done) => {
 const user = //....find User in DB, fetch roles, additional data or whatever
 // do whatever with decoded payload and call done
 // if everything is OK, call
 done(null, user);
 //whatever you pass back as "user" object will be available in route handler as req.user

 //if your user does not authenticate or anything call
 done(null, false);
}

const apiJwtOptions: any = {};
apiJwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
apiJwtOptions.algorithms = [your.jwt.alg];
apiJwtOptions.secretOrKey = your.jwt.secret;
//apiJwtOptions.issuer = ???;
//apiJwtOptions.audience = ???;
passport.use('jwt-api', new JwtStrategy(apiJwtOptions, jwtAuth));

如果您只想解码令牌,请在done(null, payload)中调用jwtAuth

然后,当您要保护端点并获取有关用户的信息时,请在路由文件中将其用作:

const router = express.Router();
router.use(passport.authenticate('jwt-api', {session: false}));

在处理程序中,您应该有req.user可用。可以根据您存储auth数据的req的属性来配置,req.user只是默认属性。