App Identity API 可讓應用程式找到自己的應用程式 ID (也稱為專案 ID)。使用這個 ID,App Engine 應用程式就可以向其他 App Engine 應用程式、Google API 及第三方應用程式與服務宣告自己的身分。此應用程式 ID 也可用來產生網址或電子郵件地址,或是建立執行階段決策。
在應用程式處理常式中,您可以讀取 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. */publicStringcreateShortUrl(StringlongUrl)throwsException{ArrayList<String>scopes=newArrayList<>();scopes.add("https://www.googleapis.com/auth/urlshortener");finalAppIdentityServiceappIdentity=AppIdentityServiceFactory.getAppIdentityService();finalAppIdentityService.GetAccessTokenResultaccessToken=appIdentity.getAccessToken(scopes);// The token asserts the identity reported by appIdentity.getServiceAccountName()JSONObjectrequest=newJSONObject();request.put("longUrl",longUrl);URLurl=newURL("https://www.googleapis.com/urlshortener/v1/url?pp=1");HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();connection.setDoOutput(true);connection.setRequestMethod("POST");connection.addRequestProperty("Content-Type","application/json");connection.addRequestProperty("Authorization","Bearer "+accessToken.getAccessToken());OutputStreamWriterwriter=newOutputStreamWriter(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.JSONTokenerresponseTokens=newJSONTokener(connection.getInputStream());JSONObjectresponse=newJSONObject(responseTokens);return(String)response.get("id");}else{try(InputStreams=connection.getErrorStream();InputStreamReaderr=newInputStreamReader(s,StandardCharsets.UTF_8)){thrownewRuntimeException(String.format("got error (%d) response %s from %s",connection.getResponseCode(),CharStreams.toString(r),connection.toString()));}}}
getAccessToken() 產生的憑證只適用於 Google 服務。但您可以使用基本的簽署技術,向其他服務宣告應用程式的身分。signForApp() 方法會利用應用程式專用的私密金鑰簽署位元組,而 getPublicCertificatesForApp() 方法會傳回可用來驗證簽名的憑證。
以下範例說明如何簽署 blob 並驗證其簽名:
// Note that the algorithm used by AppIdentity.signForApp() and// getPublicCertificatesForApp() is "SHA256withRSA"privatebyte[]signBlob(byte[]blob){AppIdentityService.SigningResultresult=appIdentity.signForApp(blob);returnresult.getSignature();}privatebyte[]getPublicCertificate()throwsUnsupportedEncodingException{Collection<PublicCertificate>certs=appIdentity.getPublicCertificatesForApp();PublicCertificatepublicCert=certs.iterator().next();returnpublicCert.getX509CertificateInPemFormat().getBytes("UTF-8");}privateCertificateparsePublicCertificate(byte[]publicCert)throwsCertificateException,NoSuchAlgorithmException{InputStreamstream=newByteArrayInputStream(publicCert);CertificateFactorycf=CertificateFactory.getInstance("X.509");returncf.generateCertificate(stream);}privatebooleanverifySignature(byte[]blob,byte[]blobSignature,PublicKeypk)throwsNoSuchAlgorithmException,InvalidKeyException,SignatureException{Signaturesignature=Signature.getInstance("SHA256withRSA");signature.initVerify(pk);signature.update(blob);returnsignature.verify(blobSignature);}privateStringsimulateIdentityAssertion()throwsCertificateException,UnsupportedEncodingException,NoSuchAlgorithmException,InvalidKeyException,SignatureException{// Simulate the sending app.Stringmessage="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.Certificatecert=parsePublicCertificate(publicCert);PublicKeypk=cert.getPublicKey();booleanisValid=verifySignature(blob,blobSignature,pk);returnString.format("isValid=%b for message: %s\n\tsignature: %s\n\tpublic cert: %s",isValid,message,Arrays.toString(blobSignature),Arrays.toString(publicCert));}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-06-16 (世界標準時間)。"],[[["The `REGION_ID` is a Google-assigned code based on the region selected during app creation, included in App Engine URLs for apps created after February 2020, but it does not directly correspond to specific countries or provinces."],["The App Identity API allows applications to find their application ID (project ID) to verify their identity to other App Engine apps, Google APIs, and third-party services, and it can be found using the `ApiProxy.getCurrentEnvironment().getAppId()` method."],["App Engine apps use URLs with the format `https://PROJECT_ID.REGION_ID.r.appspot.com`, and the `com.google.appengine.runtime.default_version_hostname` attribute can retrieve the full hostname."],["To verify the identity of an incoming request from another App Engine app, check the `X-Appengine-Inbound-Appid` header, which is added by the URLFetch service, but is only present on requests to the app's `appspot.com` domain."],["The `getAccessToken()` method can provide OAuth 2.0 tokens for authenticating with Google APIs, while the `signForApp()` and `getPublicCertificatesForApp()` methods facilitate identity assertion to third-party services using signing and certificate validation."]]],[]]