Search code examples
jwtkeygcloudservice-accounts

gcloud iam service-accounts keys create gives invalid jwt signature error


Is there any difference between a key that I create using the gcloud iam command below vs. going thru the console to create a json key? Each results in a .json file that other than obvious differences in the private_key_id and private_key values are identical. Here are the gcloud commands I am using:

gcloud iam service-accounts create my-sa-name
gcloud projects add-iam-policy-binding my-project-id --member="serviceAccount:[email protected]" --role="roles/owner"
gcloud iam service-accounts keys create key.json --iam-account=serviceAccount:[email protected]

However, when I try and leverage the one pulled down thru the command line, I get:

google.auth.exceptions.RefreshError: ('invalid_grant: Invalid JWT Signature.', '{"error":"invalid_grant","error_description":"Invalid JWT Signature."}')

Oddly if I go to the console, create a key for the same service account, and put the file that downloads to my computer in place of the one from the CLI, all works fine.

How am I using the key you ask? I'm using the function-frameworks to locally run and debug a cloud function that will access a cloud storage bucket, so my code is using the google.cloud.storage client library (python 3.8). I run the local process with the environment variable GOOGLE_APPLICATION_CREDENTIALS set to the location/filename of the json key file. I know this all works fine b/c of the console-downloaded key working fine.

I have also tried using gcloud auth service-account --key-file=key.json and this also gives me the Invalid JWT Signature error.

Fortunately I'm not blocked b/c I can use the manually-created key, but I would REALLY like to automate every possible step here...

So... can anyone explain this? Seen it, figured it out and know how to fix it?


Solution

  • gcloud iam service-accounts keys create key.json \
    [email protected]
    

    One way to clarify this is:

    ACCOUNT="[[YOUR-ACCOUNT]]"
    PROJECT="[[YOUR-PROJECT]]"
    EMAIL="${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com"
    
    gcloud iam service-accounts create ${ACCOUNT} \
    --project=${PROJECT}
    
    gcloud projects add-iam-policy-binding ${PROJECT} \
    --member="serviceAccount:${EMAIL}" \
    --role="roles/owner"
    
    gcloud iam service-accounts keys create ${ACCOUNT}.json \
    --iam-account=${EMAIL} \
    --project=${PROJECT}