首页 > 解决方案 > 如何将 Passport.js Google OAuth2 策略与 Google api 一起使用?

问题描述

我已将护照 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.jsexpressgoogle-apipassport.jspassport-google-oauth

解决方案


auth的例子中有什么?

你有没有尝试过:

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

        const drive = google.drive({
            version: 'v3',
            auth: oauth2Client
        });

推荐阅读