Dkova
Dkova

Reputation: 1097

Cloud Function get access token for `getIamPolicy`

I'm using cloud functions with python as the serverless to my project I by triggering the Cloud Function to add a user to my BigQuery project so he can have access to some tables.

I need to get access token from gsutil in order to use the API to give user access permissions.

How can I give IAM role or get access token to my project so I can use it from my Cloud Function to give users (by email) access to my BigQuery.

I'm using those API endpoints:

ENDPOING_GETIAMPOLICY = 'https://cloudresourcemanager.googleapis.com/v1/projects/{resource}:getIamPolicy'
ENDPOING_SETIAMPOLICY = 'https://cloudresourcemanager.googleapis.com/v1/projects/{resource}:setIamPolicy'

In order to use this ENDPOING_GETIAMPOLICY endpoint, I need ACCESS_TOKEN

# Preparing get all the current iam users
params = {
 'access_token': ACCESS_TOKEN
}
resp = requests.post(ENDPOING_GETIAMPOLICY.format(resource=resource), params=params)

I'm open to other suggestions for how to do it.

Upvotes: 1

Views: 330

Answers (1)

Andrei Cusnir
Andrei Cusnir

Reputation: 2805

In order to get the token using Python, you can do something similar to this:

Add this to requirements.txt:

oauth2client>=4.1.2

Retrieve the token in the Cloud Function like this:

def getAccessToken():

    from oauth2client.client import GoogleCredentials
    credentials = GoogleCredentials.get_application_default()
    credentials.get_access_token()
    token = credentials.access_token

    return verifyToken(token)

def verifyToken(token):
    import requests
    response = requests.get('https://www.googleapis.com/bigquery/v2/projects/[PROJECT_ID]/datasets', headers={'Authorization': 'Bearer ' + token})

    return (response.content)  

This will return you the Access Token in String format, you can then add it to the JSON if that is what you need.

Upvotes: 2

Related Questions