Java 適用的 App Identity API 總覽

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

取得應用程式 ID

您可以使用 ApiProxy.getCurrentEnvironment().getAppId() 方法找出應用程式 ID。

取得應用程式主機名稱

根據預設,App Engine 應用程式是由 http://<your_app_id>.appspot.com 格式的網址提供服務,其中應用程式 ID 是主機名稱的一部分。如果應用程式是由自訂網域提供服務,則可能需要擷取完整的主機名稱元件。您可以使用 CurrentEnvironmentcom.google.appengine.runtime.default_version_hostname 屬性執行此操作。

Java 8

@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"));
}

Java 7

@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 如果存在,便能確切指出。

為了將這個標頭加入要求,發出要求的應用程式必須告知 URLFetch 服務不要遵循重新導向。也就是說,如果您的應用程式使用 URLFetchService 類別,則必須指定 doNotFollowRedirect。如果您的應用程式使用 java.net,則必須依照下列方式設定連線:connection.setInstanceFollowRedirects(false); 接著 App Engine 會自動將標頭新增至 HTTP 回應。

在應用程式處理常式中,您可以讀取 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 呼叫。

Java 8

/**
 * 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<String>();
  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()));
    }
  }
}

Java 7

/**
 * 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<String>();
  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 並驗證其簽名:

Java 8

// 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));
}

Java 7

// 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";
  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 值區,其中包含 5GB 的免費儲存空間及免費的 I/O 作業配額。這個值區的儲存空間上限為 5 GB;如要增加儲存空間,可以為您的應用程式啟用計費功能,並支付額外儲存空間的費用,讓這個值區成為付費值區。

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

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Java 適用的 App Engine 標準環境