首页 > 解决方案 > 如何将 python3 标准环境应用引擎 url 的请求限制为单个服务帐户?

问题描述

我有一个可在 /healthcheck 访问的 python37 标准 env 应用程序引擎 url。我已经生成了一个服务帐户密钥并保存为 json。
使用所有预期的字段:

  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "project@appspot.gserviceaccount.com",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": ""

我想以两种不同的方式调用网址:

  1. 手动请求我的 URL,并以某种方式将服务帐户字段用作身份验证请求中的标头。
  2. 安排 cron 作业运行调用相同的 URL。

我在Google Cloud上找到的所有文档仅讨论应用引擎 url 请求下游的身份验证。是否有一种标准方法可以将应用引擎 url 请求限制为一个服务帐户?

标签: google-app-engineoauth-2.0service-accountsgoogle-app-engine-python

解决方案


而不是使用 Google Cloud 提供的任何服务来确保安全。我只是用一个组成的 api 密钥创建了一个参数,并强制所有连接为 https。

在 main.py 中,我使用了烧瓶功能 @app.before_request 来检查 cron 执行或变量。

@app.before_request
def do_something_whenever_a_request_comes_in():
    if 'X-Appengine-Cron' in request.headers:
        if not request.headers['X-Appengine-Cron']:
            return 'Not Authorized', 401
    elif 'apikey' in request.args:
        print (request.args['apikey'])
        if (request.args['apikey'] != config.apikey):
        return 'Not Authorized', 401
    else:
       return 'Not Authorized', 401
    print('Passed authorization')

推荐阅读