NextJS Google Drive API使用服务帐户获取权限不足

sz81bmfz  于 2023-04-11  发布在  Go
关注(0)|答案(1)|浏览(125)

我正在编写一个简单的NextJS应用程序来列出Google Drive文件夹中的文件。

  • G驱动器文件夹归我的个人帐户所有,并与在GCP中创建的服务帐户共享
  • creds.json包含添加到服务帐户上的正确密钥

代码很简单,并且已经在许多其他教程(12)中看到:

const credsDir = path.join(process.cwd(), '.');
const credsFile = fs.readFileSync(credsDir + '/creds.json', 'utf-8');
const credsJson = JSON.parse(credsFile);

const authClient = new google.auth.GoogleAuth({
  credsJson,
  scopes: "https://www.googleapis.com/auth/drive"
});

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

const response = await drive.files.list()
// Also tried drive.files.list({ driveId: xxxxxxxxxxxxxxxxx })
// Also tried other operations besides listing files

收到的错误为:

error - GaxiosError: Insufficient Permission
    at Gaxios._request [...] {
  response: {
    config: {
      url: 'https://www.googleapis.com/drive/v3/files',
      method: 'GET',
      userAgentDirectives: [Array],
      paramsSerializer: [Function (anonymous)],
      headers: [Object],
      params: {},
      validateStatus: [Function (anonymous)],
      retry: true,
      responseType: 'json',
      retryConfig: [Object]
    },
    data: { error: [Object] },
    headers: {
      'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
      'cache-control': 'private',
      connection: 'close',
      'content-encoding': 'gzip',
      'content-type': 'application/json; charset=UTF-8',
      date: 'Fri, 07 Apr 2023 09:40:28 GMT',
      server: 'ESF',
      'transfer-encoding': 'chunked',
      'www-authenticate': 'Bearer realm="https://accounts.google.com/", error="insufficient_scope", scope="https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.appfolder https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.resource https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.readonly.metadata https://www.googleapis.com/auth/drive.photos.readonly https://www.googleapis.com/auth/drive.readonly"',
      'x-content-type-options': 'nosniff',
      'x-frame-options': 'SAMEORIGIN',
      'x-xss-protection': '0'
    },
    status: 403,
    statusText: 'Forbidden',
    request: { responseURL: 'https://www.googleapis.com/drive/v3/files' }
  },
  config: {
    url: 'https://www.googleapis.com/drive/v3/files',
    method: 'GET',
    userAgentDirectives: [ [Object] ],
    paramsSerializer: [Function (anonymous)],
    headers: {
      'x-goog-api-client': 'gdcl/6.0.4 gl-node/17.9.0 auth/8.7.0',
      'Accept-Encoding': 'gzip',
      'User-Agent': 'google-api-nodejs-client/6.0.4 (gzip)',
      Authorization: '<some bearer token>',
      Accept: 'application/json'
    },
    params: {},
    validateStatus: [Function (anonymous)],
    retry: true,
    responseType: 'json',
    retryConfig: {
      currentRetryAttempt: 0,
      retry: 3,
      httpMethodsToRetry: [Array],
      noResponseRetries: 2,
      statusCodesToRetry: [Array]
    }
  },
  code: 403,
  errors: [
    {
      message: 'Insufficient Permission',
      domain: 'global',
      reason: 'insufficientPermissions'
    }
  ],
  page: '/api/gdrive-images'
}

有一些解决方案,但都很旧,似乎不符合我的特殊情况。
我可能会错过什么愚蠢的配置?

js5cn81o

js5cn81o1#

虽然我不知道我是否能正确理解你现在的问题,下面的修改如何?

发件人:

const credsDir = path.join(process.cwd(), '.');
const credsFile = fs.readFileSync(credsDir + '/creds.json', 'utf-8');
const credsJson = JSON.parse(credsFile);

const authClient = new google.auth.GoogleAuth({
  credsJson,
  scopes: "https://www.googleapis.com/auth/drive"
});

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

const response = await drive.files.list()

收件人:

const credsDir = path.join(process.cwd(), '.');
const authClient = new google.auth.GoogleAuth({
  keyFile: credsDir + '/creds.json',
  scopes: "https://www.googleapis.com/auth/drive",
});
const drive = google.drive({ version: 'v3', auth: authClient });
const response = await drive.files.list()
  • 当我测试这个修改后的脚本时,没有发生错误,我确认response.data包括服务帐户的驱动器的文件列表。

参考:

  • 使用Google API的keyFile属性Node.js客户端

相关问题