连接到 Google Cloud 服务

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

启用 openid 范围

需要 openid 范围才能生成 OpenID Connect ID 令牌。您还必须列出脚本使用的任何其他范围,例如 UrlFetch 服务的 https://www.googleapis.com/auth/script.external_request。此示例中包含 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());
}