Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

How to properly use Service Accounts with Clients (Python API + Gmail API)

Hey Yall, im a student whose totally new to GCP, working on a startup idea i have and I am trying to figure out the correct way to access my teams Gmails to help us develop our own custom KPI tracking. I have a project with a service account and service account key. I am trying to use the service account to impersonate me and my team and digest their emails so I can send them to S3. Below is the python code I am using to test everything out

 

 

def get_google_credentials():
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
        # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                "creds.json", SCOPES
            )
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open("token.json", "w") as token:
            token.write(creds.to_json())

    return creds

def get_credential(user):
  credentials = service_account.Credentials.from_service_account_file(
      SERVICE_ACCOUNT_FILE, scopes=SCOPES)
  delegated_credentials = credentials.with_subject(user)

  return delegated_credentials


def get_gmail_users(creds):
    admin_service = build("admin", "directory_v1", credentials=creds)
    google_users = admin_service.users().list(customer="my_customer", orderBy="email").execute().get('users', [])
    return google_users


def get_gmail_threads_by_user(user_id, creds):
    gmail_service = build("gmail", "v1", credentials=creds)
    emails = gmail_service.users().messages().list(userId=user_id).execute().get('messages', [])
    return emails

 

Here is there error I get everytime I run the code,

google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.',

I have looked at 7 different stackoverflow posts  to try and figure out where I am going wrong but none of their solutions worked for me
https://stackoverflow.com/questions/72580300/google-api-call-using-service-account-returns-400-inval...

https://stackoverflow.com/questions/62045825/having-issues-using-create-delegated-in-oauth-google-ap...

https://stackoverflow.com/questions/53441806/client-is-unauthorized-to-retrieve-access-tokens-using-...

https://stackoverflow.com/questions/50987584/unauthorized-client-client-is-unauthorized-to-retrieve-...

https://stackoverflow.com/questions/76926042/how-do-i-debug-unauthorized-client-error-in-a-google-ap...

https://stackoverflow.com/questions/73404879/unauthorized-client-error-when-trying-to-impersonate-an...

https://stackoverflow.com/questions/55325978/client-is-unauthorized-to-retrieve-access-tokens-using-...

0 2 626
2 REPLIES 2

Hi @cekcreator

Welcome to Google Cloud Community!

Have you tried to run it again? It might take up to 24 hours for authorization to propagate to all users in your Google Account. Ensure to enable the IAM Service Account Credentials API in your project. Ensure also that the service account is authorized in the Domain-wide delegation page of the Admin console.

If you already authorized the service account, please ensure if it was authorized using the client ID (numeric) instead of email address in the Admin console. Please see JWT error codes of OAuth for more information.

Have a look also at this SO thread as it might give you some insights on how to make it work. You can also check this sample code from GitHub on how to impersonate a user for your reference.

Was this helpful? If so, please accept this answer as “Solution”. If you need additional assistance, reply here within 2 business days and I’ll be happy to help.

Thank you so much! I think waiting was the issue, I had seen somewhere that it could take an hour to propagate but I think it took longer. Thank you!