アプリケーション ハンドラでは、X-Appengine-Inbound-Appid ヘッダーを読み取り、リクエストを行うことを許可された ID のリストと比較することで受信 ID を確認できます。
Google API に ID を表明する
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()));}}}
アプリケーションの ID はサービス アカウント名で表されます。通常は applicationid@appspot.gserviceaccount.com となります。正確な値を取得するには、getServiceAccountName() メソッドを使用します。ACL を提供するサービスでは、このアカウントのアクセスを許可することでアプリケーションにアクセスを許可します。
サードパーティのサービスに ID を表明する
getAccessToken() によって生成されたトークンは、Google サービスでのみ有効です。ただし、基盤となる署名テクノロジーを使用してアプリケーションの ID をその他のサービスに表明できます。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-09-04 UTC。"],[[["\u003cp\u003eThe \u003ccode\u003eREGION_ID\u003c/code\u003e 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.\u003c/p\u003e\n"],["\u003cp\u003eThe 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 \u003ccode\u003eApiProxy.getCurrentEnvironment().getAppId()\u003c/code\u003e method.\u003c/p\u003e\n"],["\u003cp\u003eApp Engine apps use URLs with the format \u003ccode\u003ehttps://PROJECT_ID.REGION_ID.r.appspot.com\u003c/code\u003e, and the \u003ccode\u003ecom.google.appengine.runtime.default_version_hostname\u003c/code\u003e attribute can retrieve the full hostname.\u003c/p\u003e\n"],["\u003cp\u003eTo verify the identity of an incoming request from another App Engine app, check the \u003ccode\u003eX-Appengine-Inbound-Appid\u003c/code\u003e header, which is added by the URLFetch service, but is only present on requests to the app's \u003ccode\u003eappspot.com\u003c/code\u003e domain.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003egetAccessToken()\u003c/code\u003e method can provide OAuth 2.0 tokens for authenticating with Google APIs, while the \u003ccode\u003esignForApp()\u003c/code\u003e and \u003ccode\u003egetPublicCertificatesForApp()\u003c/code\u003e methods facilitate identity assertion to third-party services using signing and certificate validation.\u003c/p\u003e\n"]]],[],null,[]]