【问题标题】:How to use Passport.js Google OAuth2 strategy with Google api?如何将 Passport.js Google OAuth2 策略与 Google api 一起使用?
【发布时间】:2020-12-09 11:32:21
【问题描述】:

我已将护照 google oauth 2.0 添加到我的网站,它工作正常。

这是对 google 的初始身份验证调用:

router.get("/google", 
            passport.authenticate('google',  
                                  { scope:  ["https://www.googleapis.com/auth/drive", 
                                   "https://www.googleapis.com/auth/userinfo.profile"]
          }));

但是当我访问 Drive API 时,我得到一个错误。

例如,当我使用:

  const drive = google.drive({ version: "v3", auth});
  drive.files.create(
    {
      .......
}

我收到一个错误:

code: 401, errors: [ { domain: 'global', reason: 'required', message: 'Login Required', locationType: 'header', location: 'Authorization' } ]

有没有办法在登录时使用令牌并协调护照登录和api访问?

【问题讨论】:

    标签: node.js express google-api passport.js passport-google-oauth


    【解决方案1】:

    您的示例中的 auth 是什么?

    你试过了吗:

           const oauth2Client = new google.auth.OAuth2()
            oauth2Client.setCredentials({
                'access_token': req.user.accessToken
            });
    
            const drive = google.drive({
                version: 'v3',
                auth: oauth2Client
            });
    

    【讨论】:

    • auth 在我的例子中是 ; auth = new google.auth.OAuth2(ClientId, ClientSecret, RedirectionUrl );我试过这个,但我得到了这个错误:Error: No access, refresh token or API key is set.
    • @Aditya 你试过设置 access_token 吗? oauth2Client.setCredentials({'access_token': req.user.accessToken});
    • 这很有效。 oauth2Client.setCredentials({'access_token': req.user.accessToken}); 。我以req.user.access_token 的身份访问访问令牌。
    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 2022-01-21
    • 2015-08-16
    • 2012-02-01
    • 1970-01-01
    • 2013-01-13
    • 2018-05-03
    • 2015-09-07
    相关资源
    最近更新 更多