App Identity API 可讓應用程式找到自己的應用程式 ID (也稱為專案 ID)。使用這個 ID,App Engine 應用程式就可以向其他 App Engine 應用程式、Google API 及第三方應用程式與服務宣告自己的身分。此應用程式 ID 也可用來產生網址或電子郵件地址,或是建立執行階段決策。
取得專案 ID
您可以使用 app_identity.get_application_id() 方法找出專案 ID。WSGI 或 CGI 環境會公開一些由 API 處理的實作詳情。
取得應用程式主機名稱
根據預設,App Engine 應用程式是由 https://PROJECT_ID.REGION_ID.r.appspot.com 格式的網址提供服務,其中專案 ID 是主機名稱的一部分。如果應用程式是由自訂網域提供服務,則可能需要擷取完整的主機名稱元件。您可以使用 app_identity.get_default_version_hostname() 方法執行這項操作。
在應用程式處理常式中,您可以讀取 X-Appengine-Inbound-Appid 標頭並比對允許發出要求的 ID 清單,藉此檢查傳入的 ID。例如:
importwebapp2classMainPage(webapp2.RequestHandler):allowed_app_ids=["other-app-id","other-app-id-2"]defget(self):incoming_app_id=self.request.headers.get("X-Appengine-Inbound-Appid",None)ifincoming_app_idnotinself.allowed_app_ids:self.abort(403)self.response.write("This is a protected page.")app=webapp2.WSGIApplication([("/",MainPage)],debug=True)
向 Google API 宣告身分
Google API 使用 OAuth 2.0 通訊協定進行驗證及授權。App Identity API 可建立 OAuth 憑證,用來宣告要求來源是應用程式本身。get_access_token() 方法會傳回單一範圍或列有多範圍清單的存取憑證。接著可在呼叫的 HTTP 標頭中設定這個憑證,以識別呼叫應用程式。
以下範例顯示如何使用 App Identity API 驗證 Cloud Storage API,並且擷取專案中所有值區的清單。
importjsonimportloggingfromgoogle.appengine.apiimportapp_identityfromgoogle.appengine.apiimporturlfetchimportwebapp2classMainPage(webapp2.RequestHandler):defget(self):auth_token,_=app_identity.get_access_token("https://www.googleapis.com/auth/cloud-platform")logging.info("Using token {} to represent identity {}".format(auth_token,app_identity.get_service_account_name()))response=urlfetch.fetch("https://www.googleapis.com/storage/v1/b?project={}".format(app_identity.get_application_id()),method=urlfetch.GET,headers={"Authorization":"Bearer {}".format(auth_token)},)ifresponse.status_code!=200:raiseException("Call failed. Status code {}. Body {}".format(response.status_code,response.content))result=json.loads(response.content)self.response.headers["Content-Type"]="application/json"self.response.write(json.dumps(result,indent=2))app=webapp2.WSGIApplication([("/",MainPage)],debug=True)
get_access_token() 產生的憑證只適用於 Google 服務。但您可以使用基本的簽署技術,向其他服務宣告應用程式的身分。sign_blob() 方法會利用應用程式專用的私密金鑰簽署位元組,而 get_public_certificates() 方法會傳回可用來驗證簽名的憑證。
以下範例說明如何簽署 blob 並驗證其簽章:
importbase64fromCrypto.HashimportSHA256fromCrypto.PublicKeyimportRSAfromCrypto.SignatureimportPKCS1_v1_5fromCrypto.Util.asn1importDerSequencefromgoogle.appengine.apiimportapp_identityimportwebapp2defverify_signature(data,signature,x509_certificate):"""Verifies a signature using the given x.509 public key certificate."""# PyCrypto 2.6 doesn't support x.509 certificates directly, so we'll need# to extract the public key from it manually.# This code is based on https://github.com/google/oauth2client/blob/master# /oauth2client/_pycrypto_crypt.pypem_lines=x509_certificate.replace(b" ",b"").split()cert_der=base64.urlsafe_b64decode(b"".join(pem_lines[1:-1]))cert_seq=DerSequence()cert_seq.decode(cert_der)tbs_seq=DerSequence()tbs_seq.decode(cert_seq[0])public_key=RSA.importKey(tbs_seq[6])signer=PKCS1_v1_5.new(public_key)digest=SHA256.new(data)returnsigner.verify(digest,signature)defverify_signed_by_app(data,signature):"""Checks the signature and data against all currently valid certificates for the application."""public_certificates=app_identity.get_public_certificates()forcertinpublic_certificates:ifverify_signature(data,signature,cert.x509_certificate_pem):returnTruereturnFalseclassMainPage(webapp2.RequestHandler):defget(self):message="Hello, world!"signing_key_name,signature=app_identity.sign_blob(message)verified=verify_signed_by_app(message,signature)self.response.content_type="text/plain"self.response.write("Message: {}\n".format(message))self.response.write("Signature: {}\n".format(base64.b64encode(signature)))self.response.write("Verified: {}\n".format(verified))app=webapp2.WSGIApplication([("/",MainPage)],debug=True)
[[["容易理解","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-05-30 (世界標準時間)。"],[[["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 project ID, which can be used for identity assertion with other App Engine apps, Google APIs, or third-party services, as well as generating URLs or email addresses."],["App Engine apps can verify the identity of another App Engine app making a request by checking the `X-Appengine-Inbound-Appid` header, but this is only available for calls to the `appspot.com` domain and requires disabling redirects."],["The App Identity API's `get_access_token()` method generates OAuth 2.0 tokens for authentication with Google APIs, while the `sign_blob()` and `get_public_certificates()` methods allow identity assertion with non-Google services through unique application-specific key signing."],["Each application has access to a default Cloud Storage bucket that includes free storage and I/O quota, the name of which can be retrieved via the `get_default_gcs_bucket_name` method."]]],[]]