使用PassPortJS和Node.jS获取Google OAuth 2.0刷新令牌

时间:2017-04-10 18:39:03

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

我无法使用Passport JS从Google获取刷新令牌。我一直在删除帐户权限,以确保它是第一次登录。我一直为令牌“未定义”。这是我目前的代码。

Passport.use(new GoogleStrategy({
    clientID:     "xxxxx.apps.googleusercontent.com",
    clientSecret: "xxxxx",
    callbackURL: `https://localhost:${port}/auth/google/callback`,
    accessType: 'offline',
    passReqToCallback: true
  },
  function(req,accessToken, refreshToken, profile, done) {

    var tokens = {
      access_token: accessToken,
      refresh_token: refreshToken
    }
    console.log(tokens)
    oauth2Client.setCredentials(tokens);


    done(err = false, user = true)


}));

如果有人有将OAuth用于他们的网络应用程序的经验,可以提供帮助,将非常感谢

2 个答案:

答案 0 :(得分:1)

答案是在无辜的路线中请求它并且每次都创建同意提示。

app.get('/auth/google', passport.authenticate('google',{accessType: 'offline', prompt: 'consent', scope: ['openid profile email https://www.googleapis.com/auth/drive']}))

答案 1 :(得分:0)

要在NodeJS中使用passportJS获得刷新令牌,您只需在路由器部分添加另外两个访问字段( accessType: 'offline', prompt: 'consent' )

ex.router.get('/auth/google', passport.authenticate('google', {
    scope: ['profile'],
    accessType: 'offline',
    prompt: 'consent'       
}));

此后,您将收到刷新令牌。

注意:如果您的应用程序未经过Google的验证,那么它将发出警告。 只需点击下面的 advance 按钮,即可开始使用。

相关问题