在不使用 Google SDK 的情况下访问 Google CloudTasks API



我正在尝试使用Cloudflare工作人员的Google cloudtasks。这是一个仅限于web工作者标准的JS环境,减去了Cloudflare没有实现的一些东西。最重要的是,我不能在那种环境下使用谷歌提供的SDK。我试图使用简单的fetch调用API,但在身份验证部分总是失败。

发现文件说

"parameters": {
...
"key": {
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query",
"type": "string"
}
}

所以我尝试用?key=MY_API_KEY查询参数调用api没用。

我还尝试使用Service Account下载的带有此库的json文件生成令牌没用。

我尝试按照本指南生成oauth访问令牌,这正是错误消息告诉我需要的。但是

  1. 运行命令gcloud auth application-default print-access-token返回错误:
    WARNING: Compute Engine Metadata server unavailable onattempt 1 of 3. Reason: timed out
    WARNING: Compute Engine Metadata server unavailable onattempt 2 of 3. Reason: timed out
    WARNING: Compute Engine Metadata server unavailable onattempt 3 of 3. Reason: [Errno 64] Host is down
    WARNING: Authentication failed using Compute Engine authentication due to unavailable metadata server.
    ERROR: (gcloud.auth.application-default.print-access-token) Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
    
    上面的env变量已正确设置为服务帐户json文件
  2. 即使它有效,我也不明白我应该如何从代码中使用它,而它使用的是cli工具gcloud

所以我的问题是,在不使用任何CLI工具或Google SDK的情况下,我如何从Cloudflare workers(web workers javascript env.(访问Google的云API,特别是我对Cloudtasks感兴趣。更具体地说,我如何生成所需的oauth2访问令牌?

基于@john hanley的博客文章,我能够使以下代码工作:

const fetch = require('node-fetch'); //in cloudflare workers env. this is not needed. 'fetch' is globally available
const jwt = require('jsonwebtoken');
const q = require('querystring');
async function main() {
const project = 'xxxx';
const location = 'us-central1';
const scopes = "https://www.googleapis.com/auth/cloud-platform"

const queue = 'queueName';
const parent = `projects/${project}/locations/${location}/queues/${queue}`
const url = `https://cloudtasks.googleapis.com/v2/${parent}/tasks`
const sjwt = await createSignedJwt(json.private_key, json.private_key_id, json.client_email, scopes);
const {token} = await exchangeJwtForAccessToken(sjwt)
const headers = { Authorization: `Bearer ${token}` }
const body = Buffer.from(JSON.stringify({"c":"b"})).toString('base64'); //Note this is not a string!
const task = { //in my case the task is HTTP request that google will send to my service outside GCP. You can create an appEngine task instead
httpRequest: {
"url": "https://where-google-should-send-the-task.com",
"httpMethod": "POST",
"headers": {
"Content-Type": "application/json; charset=UTF-8",
"Authorization": "only-if-you-need-it"
},
"body": body
}
};
const request = {
parent: parent,
task: task
};
const response = await fetch(url, {
method: "POST",
body: JSON.stringify(request),
headers
})
const res =  await response.json()
console.log(res)
}
async function createSignedJwt (pkey, pkey_id, email, scope) {
const authUrl = "https://oauth2.googleapis.com/token"
const options = {
algorithm: "RS256",
keyid: pkey_id,
expiresIn: 3600,
audience: authUrl,
issuer: email
// header: { //this is not needed because it's jsonwebtoken's default behavior to add the correct typ when the payload is a json
//     "typ": "JWT"
// }
}
const payload = {
"scope": scope
}
return jwt.sign(payload, pkey, options)
}
/**
* This function takes a Signed JWT and exchanges it for a Google OAuth Access Token
*/
async function exchangeJwtForAccessToken(signedJwt) {
const authUrl = "https://oauth2.googleapis.com/token"
const params = {
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": signedJwt
}
const body = q.stringify(params);
const res = await fetch(authUrl, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body
})
if (!res.ok) {
return {
error: "Could not fetch access token. " + await res.text()
}
}
const resJson = await res.json();
return {
token: resJson.access_token
}
}
// for convenience, I'm placing the JSON here. For production it should be stored in secret-manager or injected via environment variable
const json = {
"type": "service_account",
"project_id": "xxxx",
"private_key_id": "xxxx",
"private_key": "-----BEGIN PRIVATE KEY-----xxxx-----END PRIVATE KEY-----n",
"client_email": "xxxx@xxxx.iam.gserviceaccount.com",
"client_id": "xxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxx%40xxxx.iam.gserviceaccount.com"
}

main()

相关内容

最新更新