Search code examples
service-accountsgoogle-apis-explorergoogle-iamgoogle-cloud-iam

Calling Google IAM generateAccessToken API always returns error


I'm facing the issue where I am not able to generate an Access Token for Google IAM Service Account using this method . I've got my personal OAuth2 access token using: gcloud auth application-default print-access-token

I've got all the necessary roles (roles/iam.serviceAccountTokenCreator) but when I cURL the API I always get an error response:

{
  "error": {
    "code": 400,
    "message": "Request contains an invalid argument.",
    "status": "INVALID_ARGUMENT"
  }
}

This is how full curl request looks like:

curl -X POST --header 'Content-Type: application/json' --header 'authorization: Bearer ya29.AASDSADASDASDi9C1yAXXXXXXZzLtDDrCAzblqF_qi5sKvMZcHieBADASDASDTNJiOKrqJBffb4Moh3gTgiTbDgMIF1XDQU5JZ31aACs0aUbI4wgeqV2Q' https://iamcredentials.googleapis.com/v1/projects/<PROJECT_NAME>/serviceAccounts/<SA_NAME>@<PROJECT_NAME>.iam.gserviceaccount.com:generateAccessToken -d '{"scope": ["https://www.googleapis.com/auth/cloud-platform"]}'

Thanks


Solution

  • You have two problems in your API call.

    1. The Service Account Name is a path parameter and must be URL encoded. The @ character is not valid. Use %40 in its place (as an example of correct encoding).
    2. The URI specifies a PROJECT_NAME. This is not correct. You need to use a - (hyphen/dash character). Example projects/-/serviceAccounts.

    You also need to have the permission iam.serviceAccounts.getAccessToken attached to one of the roles that are assigned to the account that created the request Access Token use in this API request. This will cause a different error if incorrect. Just a tip as you get to the next step.