首页 > 解决方案 > 在 Python 代码中识别 GCP HTTP(s) Cloud Function Invoker 的身份

问题描述

当使用以下方式调用云函数时,是否有一种简单的方法来获取调用者的用户名/电子邮件:gcloud functions call <function-name>

云功能应该为用户生成一些东西,但需要使用用户名。

使用参数传递它--data是不合适的,因为我们无法验证用户是否传递了他们自己的用户名或其他东西。

我已经在函数内部打印了标题,但它们与调用它的用户没有任何关系。

标签: pythongoogle-cloud-functions

解决方案


I ended up passing an id_token in the payload to the CF and inside it using a google python library to validate it and extract the user email.

Although not the same use case, I found some sample code here: https://developers.google.com/identity/one-tap/android/idtoken-auth

from google.oauth2 import id_token
from google.auth.transport import requests

# (Receive token by HTTPS POST)
# ...

try:
    idinfo = id_token.verify_oauth2_token(token, requests.Request())
    user_email = idinfo['email']
    #From here on I can split the email and get the username...
    #Now that I have the username, I can create the resources I needed with their username appended to the resource name.
except ValueError:
    # Invalid token
    pass

The token was passed to the CF in the payload data like this: {"identity_token":"$(gcloud auth print-identity-token)"} from user side.

Hopefully this comes in handy for someone that has similar use case.


推荐阅读