0

I am unable to authenticate properly using the following command

gcloud auth application-default login --impersonate-service-account=<sa_email>

The user I am authenticating with has the Service Account Token Creator role.

However, when executing this code, I receive the following error. I think I have done everything correctly. I don't understand what I'm doing wrong.

import google.auth
from googleapiclient.discovery import build

creds, _ = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])
service = build('sheets', 'v4', credentials=creds)
result = service.spreadsheets().values().get(
        spreadsheetId=<spreadsheet_id>, range=<range_name>).execute()

\lib\site-packages\google\auth\impersonated_credentials.py", line 103, in _make_iam_token_request raise exceptions.RefreshError(_REFRESH_ERROR, response_body) google.auth.exceptions.RefreshError: ('Unable to acquire impersonated credentials', '')

Thank you very much for your help.

p.s. iamcredentials.googleapis.com is enabled.

anselboero
  • 35
  • 1
  • 3
  • Are you sure about the service account email? In addition, add scopes when you create your credential, you can't re-scope your token after creation in your code. You can find details in that article: https://medium.com/google-cloud/google-oauth-credential-going-deeper-the-hard-way-f403cf3edf9d – guillaume blaquiere Feb 23 '23 at 08:59
  • you can also refer to this [stock overflow link](https://stackoverflow.com/questions/60554732/gcp-impersonate-service-account-as-a-user). – Jeffrey D. Feb 23 '23 at 22:09

1 Answers1

0

This is very useful documentation @guillaume blaquiere you can use this for reference.

Instead of trying to impersonate a service account from a user account, grant the user permission to create a service account OAuth access token.

Grant the user the role roles/iam.serviceAccountTokenCreator on the service account. This role is called "Service Account Token Creator" in the web console.

Call the API generateAccessToken to create an access token from the service account.

[projects.serviceAccounts.generateAccessToken][1]

A simple HTTP POST request will return an access token. Modify the following request with the service account email address.

POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE-ACCOUNT-NAME@PROJECTID.iam.gserviceaccount.com:generateAccessToken

Request Body:

{
  "delegates": [],
  "scope": [
      "https://www.googleapis.com/auth/cloud-platform"
  ],
  "lifetime": "3600s"
enter code here
}

This API requires authorization. Include the user's OAuth access token in the HTTP Authorization header.

Authorization: Bearer ACCESS_TOKEN

Response Body:

{
   "accessToken": "eyJ0eXAifeA...NiK8i",
   "expireTime": "2020-03-05T15:01:00.12345678Z"
}
Jeffrey D.
  • 414
  • 1
  • 7