在应用处理程序中,您可以通过读取 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"]],["最后更新时间 (UTC):2025-03-06。"],[[["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."]]],[]]