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 來擷取使用 OAuth 的 Google 日曆聯絡人。
// Retrieves Google Calendar contacts using OAuthuse google\appengine\api\app_identity\AppIdentityService;function setAuthHeader() { $access_token = AppIdentityService::getAccessToken('https://www.google.com/m8/feeds'); return [sprintf('Authorization: OAuth %s', $access_token['access_token'])];}$get_contacts_url = 'https://www.google.com/m8/feeds/contacts/default/full';$headers = setAuthHeader();$opts = [ 'http' => [ 'header' => implode("\r\n", $headers), ],];$context = stream_context_create($opts);$response = file_get_contents($get_contacts_url, false, $context);$xml = simplexml_load_string($response);$email = $xml->author->email;$service_account = AppIdentityService::getServiceAccountName();if (strcmp($email, $service_account) != 0) { die(sprintf('%s does not match the service account name %s.', $email, $service_account));}
[[["容易理解","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 (世界標準時間)。"],[[["\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 determine their project ID and use it to establish identity with other App Engine apps, Google APIs, and third-party services.\u003c/p\u003e\n"],["\u003cp\u003eThe project ID is available through the \u003ccode\u003eAppIdentityService::getApplicationId()\u003c/code\u003e method, and the app's default hostname can be retrieved with \u003ccode\u003eAppIdentityService::getDefaultVersionHostname()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eTo assert its identity to other App Engine apps, an application can check for the \u003ccode\u003eX-Appengine-Inbound-Appid\u003c/code\u003e header in incoming requests, ensuring the request is from an appspot.com domain and does not follow redirects.\u003c/p\u003e\n"],["\u003cp\u003eThe App Identity API can generate OAuth 2.0 access tokens using \u003ccode\u003egetAccessToken()\u003c/code\u003e for authentication and authorization with Google APIs, or use \u003ccode\u003esignForApp()\u003c/code\u003e and \u003ccode\u003egetPublicCertificates()\u003c/code\u003e for non-Google third-party services.\u003c/p\u003e\n"]]],[],null,["# App Identity API for legacy bundled services\n\n### Region ID\n\nThe \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e is an abbreviated code that Google assigns\nbased on the region you select when you create your app. The code does not\ncorrespond to a country or province, even though some region IDs may appear\nsimilar to commonly used country and province codes. For apps created after\nFebruary 2020, \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e`.r` is included in\nApp Engine URLs. For existing apps created before this date, the\nregion ID is optional in the URL.\n\nLearn more\n[about region IDs](/appengine/docs/legacy/standard/php/how-requests-are-routed#region-id). \nOK\n\nThe App Identity API lets an application discover its application ID (also\ncalled the [project ID](https://support.google.com/cloud/answer/6158840)). Using\nthe ID, an App Engine application can assert its identity to other App Engine\nApps, Google APIs, and third-party applications and services. The\napplication ID can also be used to generate a URL or email address, or to make\na run-time decision.\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| php-gen2\n|\n| /services/access). If you are updating to the App Engine PHP 7/8 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/php-differences) to learn about your migration options for legacy bundled services.\n\nGetting the project ID\n----------------------\n\nThe project ID can be found using the\n\n\n`AppIdentityService::getApplicationId()` method.\n\n\nGetting the application hostname\n--------------------------------\n\nBy default, App Engine apps are served from URLs in the form\n\n`https://`\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e`.`\u003cvar translate=\"no\"\u003e\u003ca href=\"#appengine-urls\" style=\"border-bottom: 1px dotted #999\" class=\"devsite-dialog-button\" data-modal-dialog-id=\"regional_url\" track-type=\"progressiveHelp\" track-name=\"modalHelp\" track-metadata-goal=\"regionalURL\"\u003eREGION_ID\u003c/a\u003e\u003c/var\u003e`.r.appspot.com`, where the project ID is part of the hostname.\nIf an app is served from a custom domain, it may be necessary to retrieve the\nentire hostname component. You can do this using the `AppIdentityService::getDefaultVersionHostname()` method.\n\nAsserting identity to other App Engine apps\n-------------------------------------------\n\nIf you want to determine the identity of the App Engine app that is making a\nrequest to your App Engine app, you can use the request header\n`X-Appengine-Inbound-Appid`. This header is added to the request by the URLFetch\nservice and is not user modifiable, so it safely indicates the requesting\napplication's project ID, if present.\n\n**Requirements**:\n\n- Only calls made to your app's `appspot.com` domain will contain the `X-Appengine-Inbound-Appid` header. Calls to custom domains do not contain the header.\n- Your requests must be set to not follow redirects.\n\nIn your application handler, you can check the incoming ID by reading the\n`X-Appengine-Inbound-Appid` header and comparing it to a list of IDs allowed\nto make requests.\n\nAsserting identity to Google APIs\n---------------------------------\n\nGoogle APIs use the OAuth 2.0 protocol for [authentication and\nauthorization](https://developers.google.com/identity/protocols/OAuth2). The\nApp Identity API can create OAuth tokens that can be used to assert that the\nsource of a request is the application itself. The `getAccessToken()`\nmethod\nreturns an access token for a scope, or list of scopes. This token can then be\nset in the HTTP headers of a call to identify the calling application.\nThe following example shows how to use the App Identity API to retrieve Google Calendar contacts using OAuth. **Note:** the [Google API Client Libraries](https://developers.google.com/discovery/libraries) can also manage much of this for you automatically. \n\n // Retrieves Google Calendar contacts using OAuth\n\n use google\\appengine\\api\\app_identity\\AppIdentityService;\n\n function setAuthHeader() {\n $access_token = AppIdentityService::getAccessToken('https://www.google.com/m8/feeds');\n return [sprintf('Authorization: OAuth %s', $access_token['access_token'])];\n }\n\n $get_contacts_url = 'https://www.google.com/m8/feeds/contacts/default/full';\n $headers = setAuthHeader();\n $opts = [\n 'http' =\u003e [\n 'header' =\u003e implode(\"\\r\\n\", $headers),\n ],\n ];\n\n $context = stream_context_create($opts);\n\n $response = file_get_contents($get_contacts_url, false, $context);\n\n $xml = simplexml_load_string($response);\n\n $email = $xml-\u003eauthor-\u003eemail;\n $service_account = AppIdentityService::getServiceAccountName();\n\n if (strcmp($email, $service_account) != 0) {\n die(sprintf('%s does not match the service account name %s.',\n $email,\n $service_account));\n }\n\nNote that the application's identity is represented by the service account name, which is typically *applicationid@appspot.gserviceaccount.com* . You can get the exact value by using the `getServiceAccountName()` method.\nFor services which offer ACLs, you can grant the application access by granting this account access.\n\nAsserting identity to third-party services\n------------------------------------------\n\nThe token generated by `getAccessToken()`\nonly works against Google services. However you can use the underlying signing technology to assert the identity of your application to other services. The `signForApp()` method\nwill sign bytes using a private key unique to your application, and the `getPublicCertificates()` method\nwill return certificates which can be used to validate the signature.\n| **Note:** The certificates may be rotated from time to time, and the method may return multiple certificates. Only certificates that are currently valid are returned; if you store signed messages you will need additional key management in order to verify signatures later.\n\nGetting the default Cloud Storage Bucket name\n---------------------------------------------\n\nEach application can have one default Cloud Storage bucket, which\nincludes\n[5GB of free storage and a free quota for I/O operations](/appengine/docs/quotas#Default_Gcs_Bucket).\n\nTo get the name of the default bucket,\n\n\ncall [CloudStorageTools::getDefaultGoogleStorageBucketName](/appengine/docs/legacy/standard/php/refdocs/classes/google.appengine.api.cloud_storage.CloudStorageTools#method_getDefaultGoogleStorageBucketName).\nOr, optionally, use the value `#default#` as the bucket name, where `#default#`\nwill be automatically replaced at runtime by the application's default bucket name."]]