如何通过Apps脚本认证服务账户以调用GCP云功能?

问题描述 投票:0回答:1

我正在努力从Apps Script中运行一个GCP云功能。该云功能需要认证,但我一直收到 "401错误"。但是我一直收到 "401错误"。

在我的Google项目上。

  1. 我创建了一个需要认证的云功能
  2. 我已经创建了一个服务账户,该账户有调用(和编辑)该功能的权限。
  3. 我已经下载了该服务账户的JSON密钥,并将其保存为一个名为--的对象。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。
  • 我使用的代码是 此处 来创建我的JWT函数,我用了 https:/jwt.io,以确保其格式正确。 以确保其格式正确。
google-app-engine google-apps-script google-cloud-platform http-status-code-401
1个回答
0
投票

此解决方案 由@TheMaster在评论中发布的我的解决方案解决了这个问题。

在GCP方面,我进入并启用了计算引擎和应用引擎,然后使用这个解决方案,它工作了。

唯一奇怪的是 目标受众 请求,我不得不做了一点逆向工程来获得它。我不得不从命令行工具中获取身份令牌,然后使用jwt.io对其进行解码,得到澳元密钥......。

但撇开这些不谈,一切都很顺利。

© www.soinside.com 2019 - 2024. All rights reserved.