我如何通过Apps脚本验证服务帐户以调用GCP云功能

时间:2020-06-01 15:20:02

标签: google-app-engine google-apps-script google-cloud-platform http-status-code-401

我正在努力通过Apps脚本运行GCP云功能。云功能需要身份验证。但是我不断抛出“ 401错误”

在“我的Google项目”中;

  1. 我创建了一个需要身份验证的云功能
  2. 我已经创建了一个有权调用(和编辑)该功能的服务帐户
  3. 我已经下载了该服务帐户的JSON密钥,并将其保存为我的Apps脚本中名为 CREDS 的对象

到目前为止,这是我的脚本:

const CREDS = {....JSON Key I downloaded from Cloud Console}

function base64Encode(str){
  let encoded = Utilities.base64EncodeWebSafe(str)

  return encoded.replace(/=+$/,'')
}

function encodeJWT(){
  const privateKey = `Copied the PK from the CREDs file and replaced all the escaped whitespace as a string literal`;

  let header = JSON.stringify({
    alg: "RS256",
    typ: "JWT",
  });

  let encodedHeader = base64Encode(header);

  const now = Math.floor(Date.now() / 1000);
  let payload = JSON.stringify({
    "iss": "https://accounts.google.com",
    "azp": "OAUTH CLIENT ID I CREATED ON GCP",
    "aud": "OAUTH CLIENT ID I CREATED ON GCP",
    "sub": CREDS.client_id,
    "email": CREDS.client_email,
    "email_verified": true,
    //    "at_hash": "TMTv8_OtKA539BBRxLoTBw", //Saw this in a reverse engineered Token but didnt know what to put
    "iat": now.toString(),
    "exp": (now + 3600).toString()  
  })

  let encodedPayload = base64Encode(payload);

  let toSign = [encodedHeader, encodedPayload].join('.')
  let signature = Utilities.computeRsaSha256Signature(toSign, privateKey)
  let encodedSignature = base64Encode(signature);

  let jwt = [toSign, encodedSignature].join('.')

  return jwt;

}

function testFireStore() {
  let funcUrl = "https://[MY PROJECT].cloudfunctions.net/MyFunc"

  const token = encodeJWT()
  let options = {
    headers:{
      "Authorization": "Bearer " + token
    }
  }


  let func = UrlFetchApp.fetch(funcUrl,options)
  Logger.log(func.getContentText())
}

实际的Cloud func暂时仅提供一个“ Hello World”,并且可以在控制台中正常测试

仅供参考,我已经完成了一些步骤

  • 我已经在本地计算机上使用gcloud生成了令牌,并在我的应用脚本中使用了令牌,效果很好
  • 我已经取得了上述令牌,并在https://jwt.io上对其进行了反向工程
  • 我已使用代码here创建了我的JWT函数,并与https://jwt.io进行了核对,以确保其格式正确。

1 个答案:

答案 0 :(得分:0)

@TheMaster在对我的解决方案的评论中发布的

This Solution解决了该问题。

在GCP方面,我进入并启用了计算引擎和App Engine,然后使用了该解决方案,它就起作用了。

唯一奇怪的是, target_audience 在那里请求,我必须做一些逆向工程才能获得它。我必须从命令行工具中获取身份令牌,然后使用jwt.io对其进行解码,并获得AUD密钥...

但除此之外,每个人的工作都像魅力一样