【问题标题】:Authentication is not working for google cloud API authentication with NodeJS身份验证不适用于使用 NodeJS 进行的谷歌云 API 身份验证
【发布时间】:2021-10-14 07:16:02
【问题描述】:

我正在尝试使用 Google 服务帐户从 Google Drive 下载文件。为此,我创建了一个项目,创建了一个服务帐户和密钥。 现在,当我尝试使用 google auth api 时,它返回未定义。

请在下面找到代码。

const scope = ["https://www.googleapis.com/auth/drive"];
const authService = new google.auth.GoogleAuth({
  keyFile: "./service.json",                                                                                                                                                                                                                                            
  scopes: scope,
});

这会返回类似下面的内容,

GoogleAuth {
  checkIsGCE: undefined,
  jsonContent: null,
  cachedCredential: null,
  _cachedProjectId: null,
  keyFilename: './service.json',
  scopes: [ 'https://www.googleapis.com/auth/cloud-platform' ],
  clientOptions: undefined
}

虽然 service.json 位于同一个文件夹中并从工作区本身复制了凭据。

请告诉我。谢谢

【问题讨论】:

    标签: javascript node.js google-drive-api google-api-nodejs-client


    【解决方案1】:

    请记住,您需要与服务帐户共享文件,以便它有权下载文件。

    // service account key file from Google Cloud console.
    const KEYFILEPATH = 'C:\\ServiceAccountCred.json';
    
    // Request full drive access.
    const SCOPES = ['https://www.googleapis.com/auth/drive'];
    
    // Create a service account initialize with the service account key file and scope needed
    const auth = new google.auth.GoogleAuth({
        keyFile: KEYFILEPATH,
        scopes: SCOPES
    });
    
     const driveService = google.drive({version: 'v3', auth});
    
    var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
    var dest = fs.createWriteStream('/tmp/photo.jpg');
    driveService.files.get({
      fileId: fileId,
      alt: 'media'
    })
        .on('end', function () {
          console.log('Done');
        })
        .on('error', function (err) {
          console.log('Error during download', err);
        })
        .pipe(dest);
    

    要了解授权的工作原理,请查看File upload node.js

    【讨论】:

    • @DalmTo 我已经创建了凭证文件并与服务帐户共享。仍然。这个身份验证部分没有运气。
    • @nick 确实设法解决了这个问题?
    猜你喜欢
    • 2015-08-07
    • 1970-01-01
    • 2023-03-13
    • 2021-12-20
    • 2021-09-25
    • 2020-06-01
    • 2022-11-08
    • 2016-11-25
    • 2020-02-28
    相关资源
    最近更新 更多