我在对Google API的REST请求进行身份验证时遇到问题。通常,Google都有客户端包为您完成此操作。
现在,我正在使用文档翻译服务,它还在预览中,所以我不能使用这个包。当涉及到对REST请求进行身份验证时,文档确实令人困惑。当我使用一个包时,我用这个模板给它一个JSON凭证文件:
{
"type": "xxx",
"project_id": "xxx",
"private_key_id": "xxx",
"private_key": "xxx",
"client_email": "xxx",
"client_id": "xxx",
"auth_uri": "xxx",
"token_uri": "xxx",
"auth_provider_x509_cert_url": "xxx",
"client_x509_cert_url": "xxx"
}我是否可以发送REST请求并仅使用其中的一些数据进行身份验证,就像我使用客户端包时一样?我在一些地方看到,我应该使用这些数据生成一个令牌,并使用一个令牌进行身份验证。我需要生成和使用令牌吗?如果是,如何在NodeJS中创建令牌?
发布于 2021-05-22 08:32:38
我相信你的现状和你的目标如下。
中创建令牌
问题1的答案:
我认为这是肯定的。
问题2的答案:
我认为这是肯定的。为了使用服务帐户使用Google API,需要使用服务帐户检索访问令牌。从服务帐户检索访问令牌而不使用Node.js的googleapis的示例脚本如下所示。
示例脚本:
在本例中,使用了crypto和request两个库。另外,请设置privateKey和clientEmail。此脚本来自this post。
const cryptor = require('crypto');
const request = require('request');
const privateKey = "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
const clientEmail = "###"; // client_email of JSON file retrieved by creating Service Account
const scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Sample scope
const url = "https://www.googleapis.com/oauth2/v4/token";
const header = {
alg: "RS256",
typ: "JWT",
};
const now = Math.floor(Date.now() / 1000);
const claim = {
iss: clientEmail,
scope: scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
const signature = Buffer.from(JSON.stringify(header)).toString('base64') + "." + Buffer.from(JSON.stringify(claim)).toString('base64');
var sign = cryptor.createSign('RSA-SHA256');
sign.update(signature);
const jwt = signature + "." + sign.sign(privateKey, 'base64');
request({
method: "post",
url: url,
body: JSON.stringify({
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
}),
}, (err, res, body) => {
if (err) {
console.log(err);
return;
}
console.log(body);
});https://www.googleapis.com/auth/drive.readonly作为示例作用域。关于这一点,请根据实际情况修改作用域。结果:
当运行上述脚本时,将返回以下值。您可以使用此值中的访问令牌,并可以使用此访问令牌来使用Google API。
{
"access_token":"###",
"expires_in":3599,
"token_type":"Bearer"
}注意:
参考文献:
https://stackoverflow.com/questions/67643538
复制相似问题