【问题标题】:Get the state parameters from OAuth callback in passportjs从passportjs中的OAuth回调中获取状态参数
【发布时间】:2015-06-14 13:46:38
【问题描述】:

我正在尝试将状态参数发送到 Oauth,然后在回调中捕获它们,但我无法使其工作。那么passportjs是否支持这样的功能呢?

我的想法是将 id 作为状态参数发送到 Oauth,然后根据状态参数中的 id 发送回我的应用程序的回调,我想做一个正确的重定向。

在我启用的 Twitter 策略中

passReqToCallback: true,
state: true

我的请求应该是这样的:

app.get('/auth/twitter/:gameId/:url',
    function(req, res){
        try {
            var json = JSON.stringify({gameId: req.params.gameId, url: req.params.url});
            var encodedValues = base64url(json);
            console.log('encodedValues:'+encodedValues)
            passport.authenticate('twitter', {state:encodedValues})
        }catch (e){
            console.log(e);
        }
    }
);  

然后在回调上

app.get('/auth/twitter/callback', passport.authenticate('twitter', function(req, res, next) {
try{
    //get the state params from the res uri/body
    //decode the state params
    //redirect depending on the state.gameId
}catch(e){
    console.log('twitter exception:'+e);
}}));

我已经知道我可以将 id 保存在会话中,但我想知道是否有会话较少的方法可以通过从 url 传递此信息来做到这一点,因为它不敏感。

谢谢

【问题讨论】:

  • 你知道怎么做吗?看起来 Twitter 支持 OAuth 1 但不支持 2 所以不支持 state 参数。
  • 还没有。由于缺乏信息,我计划使用会话来存储参数。

标签: node.js oauth oauth-2.0 passport.js


【解决方案1】:

使用 oAuth 2.0,您不必为此依赖任何类型的会话。通过/auth/twitter/:gameId/:url 路由传入状态的方式,您可以使用req.query.state 访问回调中的状态。

如果其他人遇到问题,当尝试通过 oAuth 进度传递应用程序状态时,这就是我在 Node-app 中解决它的方法:

由于我想将用户重定向到不同的位置,根据用户在进入身份验证屏幕之前来自的位置,我构建了不同的访问身份验证屏幕的路径,并根据命中的路径传递不同的状态。像这样:

router.get('/google/io', passport.authenticate('google', {
    scope: ['email', 'profile'],
    state: 'io'
}));

router.get('/google/de', passport.authenticate('google', {
    scope: ['email', 'profile'],
    state: 'de'
}));

因此,如果我的用户使用 .io 域访问来自我的页面的身份验证屏幕,我的 state 参数将携带值 'io',并且如果用户访问来自我的页面的 .de 版本的身份验证屏幕,状态参数将携带'de'的值。验证成功后,我可以从req.query.state 中提取值,并将它们重定向回mypage.demypage.io

【讨论】:

    猜你喜欢
    • 2013-12-29
    • 2011-04-21
    • 2013-11-05
    • 2013-11-04
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2015-02-03
    相关资源
    最近更新 更多