gpt4 book ai didi

node.js - Passport JWT 身份验证提取 token

转载 作者:搜寻专家 更新时间:2023-10-31 23:50:33 25 4
gpt4 key购买 nike

我正在使用 express 和 jwt-simple 作为中间件 api 来处理登录/注册和经过身份验证的请求。我正在尝试创建一个众所周知的端点,以便其他 api 可以根据发送的 token 对请求进行身份验证。

这是我的策略:

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));
});

这是我的.well-known 路线:

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 });

我实际上如何在路由函数中获取 token 并解密它?所有这一切现在所做的是,如果为真,它会进行身份验证,但是我需要能够解密 token 以发回存储的值。我不确定 res.req.user.attributes 的来源,这是 token 吗?

最佳答案

看看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));

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

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

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

并且在处理程序中,您应该可以使用 req.user。您可以配置 req 的什么属性来存储来自 auth 的数据,req.user 只是默认值。

关于node.js - Passport JWT 身份验证提取 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51867111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com