在应用处理程序中,您可以通过读取 X-Appengine-Inbound-Appid 标头并将其与允许发出请求的 ID 列表进行比对来检查传入 ID。
向 Google API 声明身份
Google API 使用 OAuth 2.0 协议进行身份验证和授权。App Identity API 可以创建 OAuth 令牌,这些令牌可用于声明请求的来源是应用本身。appengine.AccessToken 函数会返回一个范围或范围列表的访问令牌。然后,可以在调用的 HTTP 标头中设置此令牌,以识别调用应用。
以下示例说明了如何使用 App Identity API 对 Google URL Shortener API 进行 REST 调用。
import("context""net/http""google.golang.org/appengine/urlfetch""golang.org/x/oauth2""golang.org/x/oauth2/google"urlshortener"google.golang.org/api/urlshortener/v1")// shortenURL returns a short URL which redirects to the provided url,// using Google's urlshortener API.funcshortenURL(ctxcontext.Context,urlstring)(string,error){transport:=&oauth2.Transport{Source:google.AppEngineTokenSource(ctx,urlshortener.UrlshortenerScope),Base:&urlfetch.Transport{Context:ctx},}client:=&http.Client{Transport:transport}svc,err:=urlshortener.New(client)iferr!=nil{return"",err}resp,err:=svc.Url.Insert(&urlshortener.Url{LongUrl:url}).Do()iferr!=nil{return"",err}returnresp.Id,nil}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):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 an application to discover its project ID and assert its identity to other App Engine apps, Google APIs, and third-party services.\u003c/p\u003e\n"],["\u003cp\u003eApp Engine apps are typically served from URLs in the form \u003ccode\u003ehttps://PROJECT_ID.REGION_ID.r.appspot.com\u003c/code\u003e, with the project ID being a part of the hostname.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eX-Appengine-Inbound-Appid\u003c/code\u003e request header can be used to verify the identity of an App Engine app making a request, but this header is only present in calls made to the app's \u003ccode\u003eappspot.com\u003c/code\u003e domain.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eappengine.AccessToken\u003c/code\u003e function can be used to generate OAuth tokens for asserting identity to Google APIs, and the \u003ccode\u003eappengine.SignBytes\u003c/code\u003e function can be used to assert identity to 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/go111/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| go\n| /services/access). If you are updating to the App Engine Go 1.12+ runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/go-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`appengine.AppID` function.\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 `appengine.DefaultVersionHostname` function.\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\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 `appengine.AccessToken` function\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 make a REST call to the Google URL Shortener API. **Note:** the [Google API Client Libraries](https://developers.google.com/discovery/libraries) can also manage much of this for you automatically. \n\n import (\n \t\"context\"\n \t\"net/http\"\n\n \t\"google.golang.org/appengine/urlfetch\"\n\n \t\"golang.org/x/oauth2\"\n \t\"golang.org/x/oauth2/google\"\n \turlshortener \"google.golang.org/api/urlshortener/v1\"\n )\n\n // shortenURL returns a short URL which redirects to the provided url,\n // using Google's urlshortener API.\n func shortenURL(ctx context.Context, url string) (string, error) {\n \ttransport := &oauth2.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/urlfetch.html#google_golang_org_appengine_urlfetch_Transport{\n \t\tSource: google.AppEngineTokenSource(ctx, urlshortener.UrlshortenerScope),\n \t\tBase: &urlfetch.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/urlfetch.html#google_golang_org_appengine_urlfetch_Transport{Context: ctx},\n \t}\n \tclient := &http.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/urlfetch.html#google_golang_org_appengine_urlfetch_Client{Transport: transport}\n\n \tsvc, err := urlshortener.New(client)\n \tif err != nil {\n \t\treturn \"\", err\n \t}\n\n \tresp, err := svc.Url.Insert(&urlshortener.Url{LongUrl: url}).Do()\n \tif err != nil {\n \t\treturn \"\", err\n \t}\n \treturn resp.Id, nil\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 `appengine.ServiceAccount` function.\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 `AccessToken`\nonly works against Google services. However you can use the underlying signing technology to assert the identity of your application to other services. The `appengine.SignBytes` function\nwill sign bytes using a private key unique to your application, and the `appengine.PublicCertificates` function\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 [DefaultBucketName](https://godoc.org/google.golang.org/appengine/file)."]]