簡體   English   中英

進行Google Cloud Endpoints API的授權調用

[英]Making Authorized Calls to an Google Cloud Endpoints API

我目前的設定

回聲教程已啟動並正在運行。 我可以使用我的機器上的python腳本來調用打開的端點,以及需要API密鑰的端點。 我無法使用Google ID令牌進行授權的API調用。 到目前為止,沒有一個Google示例可以使用。

據我了解,工作流程應該是

  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調用的示例?

主要問題是生成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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM