Skip to main content
 首页 » 编程设计

python之谷歌云函数 : How to get access tokens in cloud function for the required scope

2024年08月14日30shihaiming

我们正在偏离数据存储 scheduled export机制(谷歌建议)并采用通过 cloud scheduler 安排数据存储备份它将以 HTTP cloud function 为目标.在这里,我们想使用云功能将我们的数据存储实体导出到某个存储桶。这种偏离标准机制的原因是,我们希望在所有服务中避免重复的非应用程序特定代码。

根据 docs ,托管导出和导入服务仅可通过 Datastore 模式 Admin API(REST、RPC)使用,并且请求需要 OAuth 2.0 授权。

在云功能中,访问数据存储 API https://datastore.googleapis.com/v1/projects/<APP ID>:export , 我们需要 access_token来自范围https://www.googleapis.com/auth/datastore .

在标准的 GAE 应用程序代码中,使用 python27 运行时,我们可以按照下面的示例获取 access_token -

from google.appengine import app_identity 
 
access_token, _ = app_identity.get_access_token('https://www.googleapis.com/auth/datastore') 

但是,云函数有 Python37 运行时。所以,导入 google.appengine给出错误 error as error: ModuleNotFoundError: No module named 'google.appengine'

我们怎样才能得到access_token对于所需的范围? (以下任何一个范围)-

请建议引用 Python 代码/文档。谢谢。

请您参考如下方法:

JWT 和访问 token 是两个独立的东西。 JWT 由三部分组成,即头部、声明集和签名。另一方面,访问 token 只能从授权服务器获得。请在 this 的“附录”部分谷歌文档。我通过传递服务帐户详细信息以编码到 JWT(带有 header 和有效负载)来创建云函数。

signed_jwt = jwt.encode(payload, key, headers=additional_headers, algorithm='RS256') 
decoded_signed_jwt = signed_jwt.decode("utf-8") 

为了获取访问 token ,请引用以下代码片段。

token_endpoint = 'https://www.googleapis.com/oauth2/v4/token' 
token_req_data = { 
    'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 
    'assertion': decoded_signed_jwt 
} 
token_post_data = urllib.parse.urlencode(token_req_data).encode("utf-8") 
 
access_token_req = urllib.request.Request(token_endpoint, token_post_data) 
access_token_req.add_header('Content-Type', 'application/x-www-form-urlencoded') 
result = urllib.request.urlopen(access_token_req) 
json_str = result.read() 

此 json 字符串应包含访问 token 。在所需 API 的请求 header 中使用此访问 token 。请按以下方式更新已签名 JWT 的负载,否则您可能无法获得有效的 JWT。

'scope': 'https://www.googleapis.com/auth/cloud-platform', 
'aud': 'https://www.googleapis.com/oauth2/v4/token' 

希望这会有所帮助,感谢 Google 对这个答案的某些部分的支持。