Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Regions-ID
REGION_ID ist ein abgekürzter Code, den Google anhand der Region zuweist, die Sie beim Erstellen Ihrer Anwendung ausgewählt haben. Der Code bezieht sich nicht auf ein Land oder eine Provinz, auch wenn einige Regions-IDs häufig verwendeten Länder- und Provinzcodes ähneln können. Bei Anwendungen, die nach Februar 2020 erstellt wurden, ist REGION_ID.r in den App Engine-URLs enthalten. Bei Anwendungen, die vor diesem Datum erstellt wurden, ist die Regions-ID in der URL optional.
Mit der App Identity API können Anwendungen ihre Anwendungs-ID (auch als Projekt-ID bezeichnet) ermitteln. Mithilfe der ID können App Engine-Anwendungen ihre Identität gegenüber anderen App Engine-Anwendungen, Google APIs sowie Anwendungen und Diensten von Drittanbietern bestätigen. Die Anwendungs-ID kann auch zum Generieren einer URL oder E-Mail-Adresse oder zum Ausführen einer Laufzeitentscheidung herangezogen werden.
Projekt-ID abrufen
Die Projekt-ID lässt sich mit der Methode app_identity.get_application_id() ermitteln. Die WSGI- oder CGI-Umgebung stellt einige Implementierungsdetails bereit, die von der API verarbeitet werden.
Hostname der Anwendung abrufen
App Engine-Anwendungen werden standardmäßig über URLs im Format https://PROJECT_ID.REGION_ID.r.appspot.com bereitgestellt, wobei die Projekt-ID Teil des Hostnamens ist.
Wenn eine Anwendung von einer benutzerdefinierten Domain bereitgestellt wird, muss möglicherweise die gesamte Komponente des Hostnamens abgerufen werden. Dazu können Sie die Methode app_identity.get_default_version_hostname() verwenden.
Identität gegenüber anderen App Engine-Anwendungen bestätigen
Zum Ermitteln der Identität der App Engine-Anwendung, die eine Anfrage an Ihre App Engine-Anwendung sendet, verwenden Sie den Anfrage-Header X-Appengine-Inbound-Appid. Dieser Header wird der Anfrage vom URLFetch-Dienst hinzugefügt und kann vom Nutzer nicht geändert werden. Daher wird die ID der Anwendung, die die Anfrage ausführt (falls vorhanden), sicher angezeigt.
Anforderungen:
Nur Aufrufe, die an die Domain appspot.com Ihrer Anwendung gesendet werden, enthalten den Header X-Appengine-Inbound-Appid. Aufrufe an benutzerdefinierte Domains enthalten den Header nicht.
Ihre Anfragen müssen so eingerichtet sein, dass sie keinen Weiterleitungen folgen.
Setzen Sie den Parameter urlfetch.fetch()follow_redirects auf False.
Die eingehende ID können Sie in Ihrem Anwendungs-Handler prüfen. Vergleichen Sie dazu den Inhalt des Headers X-Appengine-Inbound-Appid mit der Liste der IDs, die Anfragen senden dürfen. Beispiel:
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)
Identität gegenüber Google APIs bestätigen
Google APIs verwenden zur Authentifizierung und Autorisierung das OAuth 2.0-Protokoll. Die App Identity API kann OAuth-Tokens erstellen, mit denen bestätigt werden kann, dass die Quelle einer Anfrage die Anwendung selbst ist. Die Methode get_access_token() gibt ein Zugriffstoken für einen Bereich oder für eine Liste von Bereichen zurück. Dieses Token kann dann in den HTTP-Headern eines Aufrufs festgelegt werden, um die aufrufende Anwendung zu identifizieren.
Das folgende Beispiel zeigt, wie mit der App Identity API eine Authentifizierung bei der Cloud Storage API durchgeführt wird und sämtliche Buckets im Projekt abgerufen und aufgelistet werden.
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)
Der Dienstkontoname gibt die Identität der Anwendung wieder. Dieser lautet in der Regel applicationid@appspot.gserviceaccount.com. Den genauen Wert können Sie mit der Methode get_service_account_name() abrufen.
Für Dienste, die ACLs anbieten, können Sie der Anwendung den Zugriff über dieses Konto gewähren.
Identität gegenüber Diensten von Drittanbietern bestätigen
Das von get_access_token() generierte Token funktioniert nur in Verbindung mit Google-Diensten. Sie können jedoch die zugrunde liegende Signaturtechnologie verwenden, um die Identität Ihrer Anwendung gegenüber anderen Diensten zu bestätigen. Die Methode sign_blob() signiert die Byte mit einem privaten Schlüssel speziell für Ihre Anwendung. Die Methode get_public_certificates() gibt Zertifikate zurück, mit denen die Signatur validiert werden kann.
Hier ist ein Beispiel für das Signieren eines Blobs und die anschließende Überprüfung der Signatur:
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)
Name des standardmäßigen Cloud Storage-Buckets abrufen
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 2025-09-03 (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 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.\u003c/p\u003e\n"],["\u003cp\u003eApp Engine apps can verify the identity of another App Engine app making a request by checking the \u003ccode\u003eX-Appengine-Inbound-Appid\u003c/code\u003e header, but this is only available for calls to the \u003ccode\u003eappspot.com\u003c/code\u003e domain and requires disabling redirects.\u003c/p\u003e\n"],["\u003cp\u003eThe App Identity API's \u003ccode\u003eget_access_token()\u003c/code\u003e method generates OAuth 2.0 tokens for authentication with Google APIs, while the \u003ccode\u003esign_blob()\u003c/code\u003e and \u003ccode\u003eget_public_certificates()\u003c/code\u003e methods allow identity assertion with non-Google services through unique application-specific key signing.\u003c/p\u003e\n"],["\u003cp\u003eEach 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 \u003ccode\u003eget_default_gcs_bucket_name\u003c/code\u003e method.\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/python/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| python3\n|\n| /services/access). If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-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`app_identity.get_application_id()`method. The WSGI or CGI environment exposes\nsome implementation details, which are handled by the API.\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 `app_identity.get_default_version_hostname()` 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. Set the `urlfetch.fetch()` [`follow_redirects`](/appengine/docs/legacy/standard/python/refdocs/google.appengine.api.urlfetch#google.appengine.api.urlfetch.fetch) parameter to `False`.\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. For example: \n\n import webapp2\n\n\n class MainPage(webapp2.RequestHandler):\n allowed_app_ids = [\"other-app-id\", \"other-app-id-2\"]\n\n def get(self):\n incoming_app_id = self.request.headers.get(\"X-Appengine-Inbound-Appid\", None)\n\n if incoming_app_id not in self.allowed_app_ids:\n self.abort(403)\n\n self.response.write(\"This is a protected page.\")\n\n\n app = webapp2.WSGIApplication([(\"/\", MainPage)], debug=True)\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 `get_access_token()` method\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 authenticate to the Cloud Storage API and retrieve and list of all buckets in the project. **Note:** the [Google API Client Libraries](https://developers.google.com/discovery/libraries) can also manage much of this for you automatically. \n\n import json\n import logging\n\n from google.appengine.api import app_identity\n from google.appengine.api import urlfetch\n import webapp2\n\n\n class MainPage(webapp2.RequestHandler):\n def get(self):\n auth_token, _ = app_identity.get_access_token(\n \"https://www.googleapis.com/auth/cloud-platform\"\n )\n logging.info(\n \"Using token {} to represent identity {}\".format(\n auth_token, app_identity.get_service_account_name()\n )\n )\n\n response = urlfetch.fetch(\n \"https://www.googleapis.com/storage/v1/b?project={}\".format(\n app_identity.get_application_id()\n ),\n method=urlfetch.GET,\n headers={\"Authorization\": \"Bearer {}\".format(auth_token)},\n )\n\n if response.status_code != 200:\n raise Exception(\n \"Call failed. Status code {}. Body {}\".format(\n response.status_code, response.content\n )\n )\n\n result = json.loads(response.content)\n self.response.headers[\"Content-Type\"] = \"application/json\"\n self.response.write(json.dumps(result, indent=2))\n\n\n app = webapp2.WSGIApplication([(\"/\", MainPage)], debug=True)\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 `get_service_account_name()` 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 `get_access_token()`\nonly works against Google services. However you can use the underlying signing technology to assert the identity of your application to other services. The `sign_blob()` method\nwill sign bytes using a private key unique to your application, and the `get_public_certificates()` 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.\nHere is an example showing how to sign a blob and validate its signature: \n\n\n import base64\n\n from Crypto.Hash import SHA256\n from Crypto.PublicKey import RSA\n from Crypto.Signature import PKCS1_v1_5\n from Crypto.Util.asn1 import DerSequence\n from google.appengine.api import app_identity\n import webapp2\n\n\n def verify_signature(data, signature, x509_certificate):\n \"\"\"Verifies a signature using the given x.509 public key certificate.\"\"\"\n\n # PyCrypto 2.6 doesn't support x.509 certificates directly, so we'll need\n # to extract the public key from it manually.\n # This code is based on https://github.com/google/oauth2client/blob/master\n # /oauth2client/_pycrypto_crypt.py\n pem_lines = x509_certificate.replace(b\" \", b\"\").split()\n cert_der = base64.urlsafe_b64decode(b\"\".join(pem_lines[1:-1]))\n cert_seq = DerSequence()\n cert_seq.decode(cert_der)\n tbs_seq = DerSequence()\n tbs_seq.decode(cert_seq[0])\n public_key = RSA.importKey(tbs_seq[6])\n\n signer = PKCS1_v1_5.new(public_key)\n digest = SHA256.new(data)\n\n return signer.verify(digest, signature)\n\n\n def verify_signed_by_app(data, signature):\n \"\"\"Checks the signature and data against all currently valid certificates\n for the application.\"\"\"\n public_certificates = app_identity.get_public_certificates()\n\n for cert in public_certificates:\n if verify_signature(data, signature, cert.x509_certificate_pem):\n return True\n\n return False\n\n\n class MainPage(webapp2.RequestHandler):\n def get(self):\n message = \"Hello, world!\"\n signing_key_name, signature = app_identity.sign_blob(message)\n verified = verify_signed_by_app(message, signature)\n\n self.response.content_type = \"text/plain\"\n self.response.write(\"Message: {}\\n\".format(message))\n self.response.write(\"Signature: {}\\n\".format(base64.b64encode(signature)))\n self.response.write(\"Verified: {}\\n\".format(verified))\n\n\n app = webapp2.WSGIApplication([(\"/\", MainPage)], debug=True)\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\nyou can use the App Identity API. Call\n[google.appengine.api.app_identity.app_identity.get_default_gcs_bucket_name](/appengine/docs/legacy/standard/python/refdocs/google.appengine.api.app_identity.app_identity)."]]