舊版套裝組合服務的 App Identity API

區域 ID

REGION_ID 是 Google 根據您在建立應用程式時選取的地區所指派的簡寫代碼。雖然某些區域 ID 可能看起來與常用的國家/地區代碼相似,但此代碼並非對應國家/地區或省份。如果是 2020 年 2 月後建立的應用程式,App Engine 網址會包含 REGION_ID.r。如果是在此日期之前建立的現有應用程式,網址中則可選擇加入地區 ID。

進一步瞭解區域 ID

App Identity API 可讓應用程式找到自己的應用程式 ID (也稱為專案 ID)。使用這個 ID,App Engine 應用程式就可以向其他 App Engine 應用程式、Google API 及第三方應用程式與服務宣告自己的身分。此應用程式 ID 也可用來產生網址或電子郵件地址,或是建立執行階段決策。

取得專案 ID

您可以使用 ApiProxy.getCurrentEnvironment().getAppId() 方法找出專案 ID。

取得應用程式主機名稱

根據預設,App Engine 應用程式是由 https://PROJECT_ID.REGION_ID.r.appspot.com 格式的網址提供服務,其中專案 ID 是主機名稱的一部分。如果應用程式是由自訂網域提供服務,則可能需要擷取完整的主機名稱元件。您可以使用 CurrentEnvironmentcom.google.appengine.runtime.default_version_hostname 屬性來完成這項作業。

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  resp.setContentType("text/plain");
  ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
  resp.getWriter().print("default_version_hostname: ");
  resp.getWriter()
      .println(env.getAttributes().get("com.google.appengine.runtime.default_version_hostname"));
}

向其他 App Engine 應用程式宣告身分

針對向您的 App Engine 應用程式發出要求的 App Engine 應用程式,您可以使用要求標頭 X-Appengine-Inbound-Appid 來辨識其身分。這個標頭是由 URLFetch 服務加入要求,使用者無法修改,因此發出要求的應用程式 ID 如果存在,便能確切指出。

必要條件:

  • 只有向您應用程式 appspot.com 網域發出的呼叫會含有 X-Appengine-Inbound-Appid 標頭。對自訂網域的呼叫不含標頭。
  • 必須將要求設定為不追蹤重新導向。 如果您使用 URLFetchService 類別,應用程式必須指定 doNotFollowRedirect。在 Java 8 執行階段上執行的應用程式預設不會使用 URLFetch 服務。如要啟用 URLFetch,請 按照這些操作說明進行。
  • 如果您的應用程式使用 java.net,請更新程式碼,以便不追蹤重新導向:
    connection.setInstanceFollowRedirects(false);

在應用程式處理常式中,您可以讀取 X-Appengine-Inbound-Appid 標頭並比對允許發出要求的 ID 清單,藉此檢查傳入的 ID。

向 Google API 宣告身分

Google API 使用 OAuth 2.0 通訊協定進行驗證及授權。App Identity API 可建立 OAuth 憑證,用來宣告要求來源是應用程式本身。getAccessToken() 方法會傳回單一範圍或列有多範圍清單的存取憑證。接著可在呼叫的 HTTP 標頭中設定這個憑證,以識別呼叫應用程式。

以下範例顯示如何使用 App Identity API 對 Google URL Shortener API 發出 REST 呼叫。

/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 */
public String createShortUrl(String longUrl) throws Exception {
  ArrayList<String> scopes = new ArrayList<>();
  scopes.add("https://www.googleapis.com/auth/urlshortener");
  final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
  final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
  // The token asserts the identity reported by appIdentity.getServiceAccountName()
  JSONObject request = new JSONObject();
  request.put("longUrl", longUrl);

  URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setDoOutput(true);
  connection.setRequestMethod("POST");
  connection.addRequestProperty("Content-Type", "application/json");
  connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

  OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
  request.write(writer);
  writer.close();

  if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    // Note: Should check the content-encoding.
    //       Any JSON parser can be used; this one is used for illustrative purposes.
    JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
    JSONObject response = new JSONObject(responseTokens);
    return (String) response.get("id");
  } else {
    try (InputStream s = connection.getErrorStream();
        InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
      throw new RuntimeException(
          String.format(
              "got error (%d) response %s from %s",
              connection.getResponseCode(), CharStreams.toString(r), connection.toString()));
    }
  }
}

請注意,應用程式身分是以服務帳戶名稱表示,通常是「applicationid@」appspot.gserviceaccount.com您可以使用 getServiceAccountName() 方法取得確切的值。對於提供 ACL 的服務,您可以透過授予這個帳戶存取權的方式來授予應用程式存取權。

向第三方服務宣告身分

getAccessToken() 產生的憑證只適用於 Google 服務。但您可以使用基本的簽署技術,向其他服務宣告應用程式的身分。signForApp() 方法會利用應用程式專用的私密金鑰簽署位元組,而 getPublicCertificatesForApp() 方法會傳回可用來驗證簽名的憑證。

以下範例說明如何簽署 blob 並驗證其簽名:
// Note that the algorithm used by AppIdentity.signForApp() and
// getPublicCertificatesForApp() is "SHA256withRSA"

private byte[] signBlob(byte[] blob) {
  AppIdentityService.SigningResult result = appIdentity.signForApp(blob);
  return result.getSignature();
}

private byte[] getPublicCertificate() throws UnsupportedEncodingException {
  Collection<PublicCertificate> certs = appIdentity.getPublicCertificatesForApp();
  PublicCertificate publicCert = certs.iterator().next();
  return publicCert.getX509CertificateInPemFormat().getBytes("UTF-8");
}

private Certificate parsePublicCertificate(byte[] publicCert)
    throws CertificateException, NoSuchAlgorithmException {
  InputStream stream = new ByteArrayInputStream(publicCert);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  return cf.generateCertificate(stream);
}

private boolean verifySignature(byte[] blob, byte[] blobSignature, PublicKey pk)
    throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
  Signature signature = Signature.getInstance("SHA256withRSA");
  signature.initVerify(pk);
  signature.update(blob);
  return signature.verify(blobSignature);
}

private String simulateIdentityAssertion()
    throws CertificateException, UnsupportedEncodingException, NoSuchAlgorithmException,
    InvalidKeyException, SignatureException {
  // Simulate the sending app.
  String message = "abcdefg " + Calendar.getInstance().getTime().toString();
  byte[] blob = message.getBytes();
  byte[] blobSignature = signBlob(blob);
  byte[] publicCert = getPublicCertificate();

  // Simulate the receiving app, which gets the certificate, blob, and signature.
  Certificate cert = parsePublicCertificate(publicCert);
  PublicKey pk = cert.getPublicKey();
  boolean isValid = verifySignature(blob, blobSignature, pk);

  return String.format(
      "isValid=%b for message: %s\n\tsignature: %s\n\tpublic cert: %s",
      isValid, message, Arrays.toString(blobSignature), Arrays.toString(publicCert));
}

取得預設的 Cloud Storage 值區名稱

每個應用程式都有一個預設的 Cloud Storage 值區,其中包含 5 GB 的免費儲存空間及免費的 I/O 作業配額

如要取得預設值區的名稱,您可以使用 App Identity API。請呼叫 AppIdentityService.getDefaultGcsBucketName