如何使用Google Cloud Platform REST API中的服务帐户进行身份验证

时间:2020-06-01 19:41:09

标签: google-cloud-platform google-cloud-datastore

我想使用服务帐户密钥对Google Cloud Platform进行REST API调用,但是我无法弄清楚如何对该调用进行身份验证。通常,我会使用提供的客户端库并将密钥传递给它,但是在这种情况下,客户端库不支持该特定端点。

这是我要呼叫的其余端点: https://cloud.google.com/datastore/docs/reference/admin/rest/v1/projects/export

我需要从nodejs应用程序进行调用,所以这是相应的客户端库: https://github.com/googleapis/nodejs-datastore

The documentation专注于一般概念,但是我找不到关于如何使用正确的凭据实际进行REST调用的具体方法。

1 个答案:

答案 0 :(得分:2)

我发现Google拥有用于nodejs的库google-auth-library,该库在内部处理所需的OAuth流。我能够使用它成功进行身份验证的呼叫。

这是代码:

const auth = await new GoogleAuth({
    keyFilename: pathToKey,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
}).getClient()

const result = await auth.request({
    url: `https://datastore.googleapis.com/v1/projects/${projectId}:export`,
    method: 'POST',
    body: JSON.stringify(payload),
})

注意,这处理了身份验证部分。我仍然必须授予服务帐户正确的特权才能使授权部分正常工作。

编辑

显然,还有一个googleapis nodejs库,它为整个REST API提供了一个瘦包装。我更喜欢直接调用其余部分,因为该库具有Typescript类型,可以检查有效载荷的形状是否正确,等等,而且我不必手动指定URL。您仍然需要google-auth-library来处理身份验证。

import {google as googleapis} from 'googleapis'

const auth = await new GoogleAuth({
    keyFilename: pathToKey,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
}).getClient()

const datastore = googleapis.datastore('v1')
await datastore.projects.export({
    auth,
    projectId: theProjectid,
    requestBody: payload,
})