连接到 Google Cloud 服务

您可以使用 ScriptApp.getIdentityToken() 方法为有效用户获取 OpenID Connect 身份令牌(JSON Web 令牌 或 JWT)。您可以使用此令牌向配置为接受此令牌的 Google Cloud 服务(例如 Cloud Run)进行身份验证。

启用 openid 范围

如需生成 OpenID Connect ID 令牌,您必须启用 openid 范围。您还必须列出脚本使用的任何其他范围,例如 https://www.googleapis.com/auth/script.external_request 服务的 UrlFetch。此示例中包含 https://www.googleapis.com/auth/userinfo.email 范围,用于将用户的电子邮件地址添加到身份令牌。

在脚本项目的 清单文件 (appsscript.json) 中,将 openid 范围和任何其他必需范围添加到 oauthScopes 数组:

{
  "timeZone": "America/New_York",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "openid",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/userinfo.email"
  ]
}

配置 Google Cloud 服务

您必须将 Google Cloud 服务配置为接受向脚本颁发的身份令牌。这通常涉及将脚本的客户端 ID 添加为允许的受众群体。

如需查找脚本的客户端 ID,您可以解码身份令牌:

function logClientId() {
  const idToken = ScriptApp.getIdentityToken();
  const body = idToken.split('.')[1];
  const decoded = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
  const payload = JSON.parse(decoded);
  Logger.log('Client ID: ' + payload.aud);
}

对于 Cloud Run,您可以 配置自定义受众群体 以允许此客户端 ID。

发出通过身份验证的请求

配置完成后,您可以将身份令牌添加到请求的 Authorization 标头中:

function callCloudRunService() {
  const idToken = ScriptApp.getIdentityToken();
  const url = 'https://your-service-url.a.run.app';

  const response = UrlFetchApp.fetch(url, {
    headers: {
      'Authorization': 'Bearer ' + idToken
    }
  });

  Logger.log(response.getContentText());
}