Google cloud platform 不使用Google'访问Google CloudTasks API;s SDK

Google cloud platform 不使用Google'访问Google CloudTasks API;s SDK,google-cloud-platform,google-api,google-cloud-tasks,Google Cloud Platform,Google Api,Google Cloud Tasks,我正在尝试使用Cloudflare workers提供的Google cloudtasks。 这是一个仅限于web workers标准的JS环境,减去Cloudflare没有实现的一些东西。 底线——我不能在那种环境下使用谷歌提供的SDK。 我试图使用简单的fetch调用API,但在身份验证部分总是失败 报告说 "parameters": { ... "key": { "description": "A

我正在尝试使用Cloudflare workers提供的Google cloudtasks。 这是一个仅限于web workers标准的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
query参数调用api 没用

我还尝试使用服务帐户下载的json文件生成令牌 没用

我试图生成oauth访问令牌,这是错误消息告诉我需要的。但是

  • 运行命令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文件
  • 即使它能工作,我也不知道如何从代码中使用它,而它使用的是cli工具
    gcloud
  • 所以我的问题是-我如何从Cloudflare workers(web workers javascript env.)访问Google的云API,特别是我对Cloudtasks感兴趣,而不使用任何CLI工具或Google SDK。 更具体地说,如何生成所需的oauth2访问令牌?

    基于@john hanley,我能够使以下代码正常工作:

    const fetch=require('node-fetch')//在云端。这是不必要的。”“获取”是全局可用的
    const jwt=require('jsonwebtoken');
    const q=require('querystring');
    异步函数main(){
    const project='xxxx';
    常量位置='us-central1';
    常量范围=”https://www.googleapis.com/auth/cloud-platform"
    常量队列='queueName';
    const parent=`projects/${project}/locations/${location}/queues/${queue}`
    常量url=`https://cloudtasks.googleapis.com/v2/${parent}/任务`
    const sjwt=wait createSignedJwt(json.private_key,json.private_key_id,json.client_email,scopes);
    const{token}=wait exchangeJwtForAccessToken(sjwt)
    const headers={Authorization:`Bearer${token}}}
    const body=Buffer.from(JSON.stringify({“c”:“b”})).toString('base64');//注意这不是一个字符串!
    const task={//在我的例子中,任务是HTTP请求,google将在GCP之外发送给我的服务。您可以创建一个appEngine任务
    httpRequest:{
    “url”:”https://where-google-should-send-the-task.com",
    “httpMethod”:“POST”,
    “标题”:{
    “内容类型”:“应用程序/json;字符集=UTF-8”,
    “授权”:“仅当您需要时”
    },
    “身体”:身体
    }
    };
    常量请求={
    家长:家长,
    任务:任务
    };
    const response=等待获取(url{
    方法:“张贴”,
    正文:JSON.stringify(请求),
    标题
    })
    const res=wait response.json()
    console.log(res)
    }
    异步函数createSignedJwt(pkey,pkey_id,email,scope){
    常量authUrl=”https://oauth2.googleapis.com/token"
    常量选项={
    算法:“RS256”,
    keyid:pkey_id,
    expiresIn:3600,
    观众:authUrl,
    发行人:电子邮件
    //header:{//这不是必需的,因为当负载是json时,添加正确的类型是jsonwebtoken的默认行为
    //“典型”:“JWT”
    // }
    }
    常数有效载荷={
    “范围”:范围
    }
    返回jwt.符号(有效负载、pkey、选项)
    }
    /**
    *此函数获取签名JWT并将其交换为Google OAuth访问令牌
    */
    异步函数exchangeJwtForAccessToken(signedJwt){
    常量authUrl=”https://oauth2.googleapis.com/token"
    常量参数={
    “授权类型”:“urn:ietf:params:oauth:grant-type:jwt-bearer”,
    “断言”:signedJwt
    }
    const body=q.stringify(参数);
    const res=等待获取(authUrl{
    方法:“张贴”,
    标题:{
    “内容类型”:“应用程序/x-www-form-urlencoded”
    },
    身体
    })
    如果(!res.ok){
    返回{
    错误:“无法获取访问令牌。”+await res.text()
    }
    }
    const resJson=wait res.json();
    返回{
    令牌:resJson.access\u令牌
    }
    }
    //为了方便起见,我将JSON放在这里。对于生产,它应该存储在secret manager中或通过环境变量注入
    常量json={
    “类型”:“服务账户”,
    “项目id”:“xxxx”,
    “私钥id”:“xxxx”,
    “私钥”:“开始私钥------xxxx------结束私钥------\n”,
    “客户电子邮件”:xxxx@xxxx.iam.gserviceaccount.com",
    “客户id”:“xxxx”,
    “auth_uri”:https://accounts.google.com/o/oauth2/auth",
    “令牌uri”:https://oauth2.googleapis.com/token",
    “身份验证提供程序\u x509\u证书\u url”:https://www.googleapis.com/oauth2/v1/certs",
    “客户端\u x509\u证书\u url”:https://www.googleapis.com/robot/v1/metadata/x509/xxxx%40xxxx.iam.gserviceaccount.com"
    }
    main()
    
    对于第1点,启用了哪些计算引擎作用域?好的,云任务不接受API密钥进行授权。您必须使用OAuth访问令牌。@JohnHanley您似乎是对的。问题是如何在不使用谷歌SDK的情况下生成OAuth访问令牌?谷歌搜索。有许多关于生成令牌的好文章。我在我的网站上写了好几篇文章,都是源代码。当然,我是先用谷歌搜索的。但是,我还是找不到它。你对自己网站的提示给了我一个起点。在将代码从python迁移到js,找到cloudtasks的正确范围(隐藏在api discovery json中)之后,我终于让它工作了。谢谢你的提示。如果有人需要,我会添加一个答案