首页 文章

对Google Cloud Endpoints API进行授权呼叫

提问于
浏览
0

我当前的设置

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

根据我的理解,工作流程应该是

  • 使用密钥文件授权服务帐户生成JWT .

  • 使用JWT生成Google ID令牌 .

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

Has anyone gotten the example to work? Does anyone have an example of making an authorized API call to an Endpoint API with a Google ID token from a service account?

1 回答

  • 2

    主要问题是生成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
    

相关问题