gpt4 book ai didi

authentication - 如何使用 Passport.js 访问 OAuth 的状态参数?

转载 作者:行者123 更新时间:2023-12-03 11:41:58 24 4
gpt4 key购买 nike

我正在使用 Passport.js 进行身份验证,并且按照 Google's OAuth2 documentation ,我传入一个状态变量:

app.get('/authenticate/googleOAuth', function(request, response) {
passport.authenticate('google', {
scope:
[
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'
],
state: { blah: 'test' }
})(request, response);
});

但是,我以后似乎无法访问该变量:
passport.use(new googleStrategy(
{
clientID: '...',
clientSecret: '...',
callbackURL: '...',
passReqToCallback: true
},
function(request, accessToken, refreshToken, profile, done) {
console.log('state: ' + request.query.state);
login(profile, done);
}));

request.query.state 未定义。 request.param("state") 也不起作用。

如何在身份验证回调后获取该变量?

最佳答案

这不起作用的原因是因为您将状态作为对象而不是字符串传递。似乎 Passport 不会为您确定该值。如果你想通过 state 参数传递一个对象,你可以这样做:

passport.authenticate("google", {
scope: [
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'
],
state: base64url(JSON.stringify(blah: 'test'))
})(request, response);

正如 Rob DiMarco 在他的回答中指出的那样,您可以访问 state回调中的参数 req.query目的。

我不确定编码应用程序状态并将其传递到 state param 是一个好主意。 OAuth 2.0 RFC Section 4.1.1将状态定义为“一个不透明的值”。它旨在用于 CSRF protection .在授权请求和回调之间保留应用程序状态的更好方法可能是:
  • 生成一些 state参数值(例如 cookie 的哈希值)
  • 使用 state 保持应用程序状态作为发起授权请求前的标识符
  • 使用 state 在回调请求处理程序中检索应用程序状态从 Google 传回的参数
  • 关于authentication - 如何使用 Passport.js 访问 OAuth 的状态参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788107/

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