Configure GCP Workload Identity
Authenticate Google Cloud workloads to Keycard with a service account identity token.
A Google Cloud workload gets a short-lived ID token for its service account from the metadata server, with your Zone as its audience. It sends the token to Keycard along with the Client ID of the Application credential it authenticates as. Keycard checks the token’s signature with Google’s public keys, then checks its audience, subject, and claims. This works on Compute Engine, Cloud Run, Cloud Run functions, App Engine, and GKE pods linked to a Google service account.
Prerequisites
Section titled “Prerequisites”- Familiarity with the concepts in Workload Identity, and with Google Cloud’s ID token docs
- A Keycard Zone and an Application for the workload
- Your Zone issuer URL, from Settings → Connection in Keycard Console
- The Keycard CLI, signed in with
keycard auth signin --org <org-id> - A dedicated service account for the workload, and its unique ID:
gcloud iam service-accounts describe <service-account-email> --format='value(uniqueId)'
Register Google as a Provider
Section titled “Register Google as a Provider”Create one Provider per Zone for Google’s issuer. Every Google Cloud project shares it. If the Zone already has one, for example for Google sign-in, use it.
keycard agent api /zones/<zone-id>/providers --org <org-id> -X POST -d '{ "name": "Google Cloud", "identifier": "https://accounts.google.com", "protocols": { "oauth2": { "issuer": "https://accounts.google.com" } }}'Keycard discovers Google’s signing keys from the issuer.
Create a token credential
Section titled “Create a token credential”-
Add the credential to the Application
Terminal window keycard agent api /zones/<zone-id>/application-credentials --org <org-id> -X POST -d '{"type": "token","version": 2,"application_id": "<application-id>","provider_id": "<google-provider-id>","subject": "<service-account-unique-id>","authentication_condition": "claims.email == \"<service-account-email>\""}'Field Value subjectThe service account’s unique ID. It is numeric, globally unique, and never reused. allowed_audienceOmitted, so it defaults to your Zone issuer URL. The workload requests its token with that audience. authentication_conditionPins the service account’s email, so the credential names a readable account. For an example token and every claim Google includes, see Google’s instance identity token contents.
-
Copy the credential’s Client ID
The response’s
identifieris the credential’s Client ID. The workload sends it asclient_id. It is not a secret.
Configure the workload
Section titled “Configure the workload”-
Run the workload as the service account
Attach the service account to the Compute Engine instance or Cloud Run service. On GKE, bind the pod’s Kubernetes service account to it. The metadata server issues tokens for this service account.
-
Set environment variables
Variable Value KEYCARD_ISSUERYour Zone issuer URL KEYCARD_CLIENT_IDThe credential’s Client ID KEYCARD_RESOURCE_URLThe Resource the workload needs a token for -
Request an ID token and exchange it
Request an ID token from the metadata server with your Zone issuer URL as the audience. Then send it as
client_assertion, with the credential’s Client ID asclient_id, in aclient_credentialsgrant:Terminal window pip install keycardai-oauthimport asyncioimport osfrom keycardai.oauth import AsyncClient, GrantTypefrom keycardai.oauth.server import GCPMetadataTokenSourceasync def get_access_token() -> str:issuer = os.environ["KEYCARD_ISSUER"]gcp_token = await GCPMetadataTokenSource(audience=issuer).identity_token()async with AsyncClient(issuer) as client:response = await client.client_credentials_grant(client_assertion=gcp_token,client_assertion_type=GrantType.JWT_BEARER_CLIENT_ASSERTION,client_id=os.environ["KEYCARD_CLIENT_ID"],resource=os.environ["KEYCARD_RESOURCE_URL"],)return response.access_tokenaccess_token = asyncio.run(get_access_token())Terminal window npm install @keycardai/oauthimport { ClientCredentialsClient } from "@keycardai/oauth";import { GCPMetadataTokenSource } from "@keycardai/oauth/server";const issuer = process.env.KEYCARD_ISSUER!;const gcpToken = await new GCPMetadataTokenSource({ audience: issuer }).identityToken();const client = new ClientCredentialsClient(issuer);const response = await client.requestToken({clientAssertion: gcpToken,clientAssertionType: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",clientId: process.env.KEYCARD_CLIENT_ID!,resource: process.env.KEYCARD_RESOURCE_URL!,});const accessToken = response.accessToken;Terminal window go get github.com/keycardai/go-sdk/oauthsource, err := oauth.NewGCPMetadataTokenSource(os.Getenv("KEYCARD_ISSUER"))if err != nil {return err}gcpToken, err := source.IdentityToken(ctx)if err != nil {return err}client := oauth.NewClientCredentialsClient(os.Getenv("KEYCARD_ISSUER"))response, err := client.RequestToken(ctx, oauth.ClientCredentialsRequest{ClientID: os.Getenv("KEYCARD_CLIENT_ID"),ClientAssertion: gcpToken,ClientAssertionType: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",Resource: os.Getenv("KEYCARD_RESOURCE_URL"),})if err != nil {return err}accessToken := response.AccessTokenTerminal window bundle add keycardai-oauthrequire "keycardai/oauth"gcp_token = Keycardai::OAuth::GCPMetadataTokenSource.new(audience: ENV.fetch("KEYCARD_ISSUER")).identity_tokenclient = Keycardai::OAuth::ClientCredentialsClient.new(issuer: ENV.fetch("KEYCARD_ISSUER"))response = client.request_token(client_id: ENV.fetch("KEYCARD_CLIENT_ID"),client_assertion: gcp_token,client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",resource: ENV.fetch("KEYCARD_RESOURCE_URL"))access_token = response.access_tokenTerminal window GCP_TOKEN=$(curl -sSfG -H "Metadata-Flavor: Google" \--data-urlencode "audience=$KEYCARD_ISSUER" \-d format=full \"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity")curl -sS "$KEYCARD_ISSUER/oauth/2/token" \-d grant_type=client_credentials \-d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \--data-urlencode "client_assertion=$GCP_TOKEN" \--data-urlencode "client_id=$KEYCARD_CLIENT_ID" \--data-urlencode "resource=$KEYCARD_RESOURCE_URL"
Verify
Section titled “Verify”Run the workload. The exchange returns an access token, and a credentials:issue event shows on the Application’s Activity tab in Keycard Console.
Troubleshooting
Section titled “Troubleshooting”Keycard returns invalid_client with Invalid client assertion when the audience, subject, or condition doesn’t match. The Audit Log records details on the failure. Decode a token from the workload to compare its claims against the credential:
curl -sSfG -H "Metadata-Flavor: Google" --data-urlencode "audience=$KEYCARD_ISSUER" -d format=full \ "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity" \ | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | {aud, sub, email}'subdoesn’t match: the workload runs as a different service account, often the Compute Engine default. Attach the dedicated service account. Don’t setsubjectto the Compute Engine default service account: every workload without its own account runs as it.emailis missing: the condition fails. Decode the token to check its claims, or remove the condition and rely onsubject.- Metadata server unreachable: the workload isn’t running on Google Cloud. The metadata server is only available inside Google Cloud.
- Metadata server returns an error on GKE: the Kubernetes service account has no
iam.gke.io/gcp-service-accountannotation. See step 1.