【问题标题】:Making Authorized Calls to an Google Cloud Endpoints API对 Google Cloud Endpoints API 进行授权调用
【发布时间】:2018-12-28 22:44:25
【问题描述】:

我的当前设置

echo 教程已启动并正在运行。我可以在我的机器上使用 python 脚本调用开放端点和需要 API 密钥的端点。我无法使用 Google ID 令牌进行授权 API 调用。到目前为止,谷歌的例子都没有奏效。

据我了解,工作流程应该是

  1. 使用密钥文件授权服务帐号生成 JWT。
  2. 使用 JWT 生成 Google ID 令牌。

Google 示例:https://cloud.google.com/endpoints/docs/openapi/service-account-authentication#using_a_google_id_token(密钥文件) 代码失败。函数 get_id_token() return res['id_token'] 失败,res 中没有 id_token。

有没有人让这个例子起作用?有没有人有使用来自服务帐户的 Google ID 令牌对 Endpoint API 进行授权 API 调用的示例?

【问题讨论】:

    标签: python-2.7 google-app-engine jwt google-cloud-endpoints


    【解决方案1】:

    主要问题是生成 JWT,适用于我的代码如下。我还没有找到更好的方法来做到这一点。如果您知道更好的方法,请在下面提交您的答案或添加评论。从 JWT 生成 Google ID 令牌的代码完全来自此处的 Google 文档 (https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/endpoints/getting-started/clients/service_to_service_google_id_token/main.py) get_id_token 函数。

    def generate_jwt(audience, json_keyfile, service_account_email):
    """Generates a signed JSON Web Token using a Google API Service Account.
        https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/endpoints/getting-started/clients/google-jwt-client.py
    """
    
    # Note: this sample shows how to manually create the JWT for the purposes
    # of showing how the authentication works, but you can use
    # google.auth.jwt.Credentials to automatically create the JWT.
    #   http://google-auth.readthedocs.io/en/latest/reference/google.auth.jwt.html#google.auth.jwt.Credentials
    
    signer = google.auth.crypt.RSASigner.from_service_account_file(json_keyfile)
    
    now = int(time.time())
    expires = now + 3600  # One hour in seconds
    
    payload = {
        'iat': now,
        'exp': expires,
        'aud': 'https://www.googleapis.com/oauth2/v4/token',
        # target_audience must match 'audience' in the security configuration in your
        # openapi spec. It can be any string.
        'target_audience': audience,
        'iss': service_account_email
    }
    
    jwt = google.auth.jwt.encode(signer, payload)
    
    return jwt
    

    【讨论】:

    • 当我使用此代码示例针对 sample-app.appspot.com/_ah/api/echo/v1/echo/email 发出请求时,我得到了 401 Unauthorized 我似乎无法对此端点进行任何授权调用
    • 您在日志中看到以下错误吗?错误:VerifiedHTTPSConnection' 对象没有属性 '_tunnel_host' 如果是这样,请尝试按照此问题的答案进行操作。 stackoverflow.com/questions/52929871/…
    • 否 - 不允许使用客户端 ID:.apps.googleusercontent.com 我认为这意味着客户端 ID 实际上无效。我最终使用了您出色示例的变体使其正常工作!
    • 我们有 nodejs 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多