MrVentzi
MrVentzi

Reputation: 669

Identify GCP HTTP(s) Cloud Function Invoker's identity inside Python code

Is there a simple way to get the Invoker's username/email when a cloud function has been called using: gcloud functions call <function-name>

The cloud function is supposed to generate something for the user, but needs to use the username.

Passing it using --data parameter is not suitable as that way, we can't verify if the user is passing their own username or something else.

I've printed the headers inside the function, but they don't contain anything to do with the User who called it.

Upvotes: 3

Views: 879

Answers (1)

MrVentzi
MrVentzi

Reputation: 669

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.

Upvotes: 2

Related Questions