Configure Kubernetes Workload Identity
Authenticate Kubernetes pods to Keycard with a projected service account token.
A pod gets a short-lived service account token from Kubernetes, 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 the cluster’s public keys, then checks its audience, subject, and claims. This works for managed clusters, such as EKS, GKE, and AKS, and for private clusters that Keycard can’t reach.
Prerequisites
Section titled “Prerequisites”- Familiarity with the concepts in Workload Identity
- A Keycard Zone and an Application for the workload
- Your Zone issuer URL, from Settings → Connection in Keycard Console
- Kubernetes 1.22 or later, and
kubectl1.24 or later with access that can read the cluster’s service account issuer discovery endpoints, such as a cluster admin - The Keycard CLI, signed in with
keycard auth signin --org <org-id> jq
Read the cluster’s issuer and signing keys
Section titled “Read the cluster’s issuer and signing keys”CLUSTER_ISSUER=$(kubectl get --raw /.well-known/openid-configuration | jq -r .issuer)kubectl get --raw /openid/v1/jwks > jwks.jsonThe issuer is the API server’s --service-account-issuer, and every service account token carries it as iss. jwks.json holds the public keys the API server verifies service account tokens with. It holds no private key material.
Register the cluster as a Provider
Section titled “Register the cluster as a Provider”Create one Provider per cluster. If Keycard can reach the cluster’s issuer, as on EKS, GKE, and AKS with the OIDC issuer turned on, set only the issuer, for example in Keycard Console. Keycard then reads the current keys from it. For a cluster Keycard can’t reach, store the cluster’s public keys on the Provider as jwks:
jq -n --arg issuer "$CLUSTER_ISSUER" --slurpfile jwks jwks.json '{ name: "Kubernetes <cluster-name>", identifier: "kubernetes-<cluster-name>", protocols: { oauth2: { issuer: $issuer, jwks: $jwks[0] } }}' > provider.json
keycard agent api /zones/<zone-id>/providers --org <org-id> -X POST < provider.json| Field | Value |
|---|---|
identifier |
Any value unique in the Zone. The issuer works if no other cluster in the Zone shares it. Clusters built with kubeadm or kind all default to https://kubernetes.default.svc.cluster.local, so give each its own identifier. |
protocols.oauth2.issuer |
The cluster’s issuer. A token’s iss must match it exactly. |
protocols.oauth2.jwks |
The cluster’s public keys, from jwks.json. Keycard verifies tokens with these keys only. |
The response’s id is the Provider ID for the credential below.
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": "<cluster-provider-id>","subject": "system:serviceaccount:<namespace>:<service-account>","authentication_condition": "claims[\"kubernetes.io\"].serviceaccount.uid == \"<service-account-uid>\""}'Field Value subjectThe pod’s service account. Match exactly, or end with *for a prefix match:system:serviceaccount:<namespace>:*trusts every service account in the namespace.allowed_audienceOmitted, so it defaults to your Zone issuer URL. The pod requests its token with that audience. authentication_conditionPins the service account’s UID: kubectl get serviceaccount <service-account> -n <namespace> -o jsonpath='{.metadata.uid}'. A service account deleted and recreated with the same name gets a new UID.Kubernetes-specific claims sit under the
kubernetes.iokey, includingnamespace,serviceaccount.name,serviceaccount.uid,pod.name,pod.uid, andnode.name. For the full claim schema and an example token, see Kubernetes’ service account private claims. -
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”-
Mount a projected token with the Keycard audience
apiVersion: v1kind: Podmetadata:name: <pod-name>namespace: <namespace>spec:serviceAccountName: <service-account>containers:- name: appimage: <image>env:- name: KEYCARD_ISSUERvalue: <keycard-issuer-url>- name: KEYCARD_CLIENT_IDvalue: <credential-id>- name: KEYCARD_RESOURCE_URLvalue: <resource-url>volumeMounts:- name: keycard-tokenmountPath: /var/run/secrets/keycardreadOnly: truevolumes:- name: keycard-tokenprojected:sources:- serviceAccountToken:audience: <keycard-issuer-url>expirationSeconds: 3600path: tokenThe kubelet refreshes the token before it expires. The minimum
expirationSecondsis 600. -
Read the token and exchange it
Read the token file on each request so rotated tokens are picked up. Send it as
client_assertion, with the credential ID asclient_id, in aclient_credentialsgrant:Terminal window pip install keycardai-oauthimport asyncioimport osfrom keycardai.oauth import AsyncClient, GrantTypefrom keycardai.oauth.server import FileTokenSourcetoken_source = FileTokenSource(token_file_path="/var/run/secrets/keycard/token")async def get_access_token() -> str:async with AsyncClient(os.environ["KEYCARD_ISSUER"]) as client:response = await client.client_credentials_grant(client_assertion=await token_source.identity_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 { FileTokenSource } from "@keycardai/oauth/server";const tokenSource = new FileTokenSource({ tokenFilePath: "/var/run/secrets/keycard/token" });const client = new ClientCredentialsClient(process.env.KEYCARD_ISSUER!);const response = await client.requestToken({clientAssertion: await tokenSource.identityToken(),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/oauthtokenSource, err := oauth.NewFileTokenSource(oauth.WithFileTokenPath("/var/run/secrets/keycard/token"),)if err != nil {return err}saToken, err := tokenSource.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: saToken,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"sa_token = Keycardai::OAuth::FileTokenSource.new(token_file_path: "/var/run/secrets/keycard/token").identity_tokenclient = Keycardai::OAuth::ClientCredentialsClient.new(issuer: ENV.fetch("KEYCARD_ISSUER"))response = client.request_token(client_id: ENV.fetch("KEYCARD_CLIENT_ID"),client_assertion: sa_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 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=$(cat /var/run/secrets/keycard/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 signature, issuer, audience, subject, or condition doesn’t match. The Audit Log records details on the failure. Decode the token to compare its claims against the Provider and credential:
kubectl exec <pod-name> -n <namespace> -- cat /var/run/secrets/keycard/token \ | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | {iss, aud, sub, uid: .["kubernetes.io"].serviceaccount.uid}'issdoesn’t match the Provider: the Provider’sissuerdiffers from the cluster’s. Compare it withkubectl get --raw /.well-known/openid-configuration | jq -r .issuer. When kube-apiserver has several--service-account-issuerflags, the first one signs tokens.- Signature fails after key rotation: the Provider’s key set doesn’t hold the key that signed the token. Read the cluster’s keys again and update the Provider’s
jwkswith all of them. uiddoesn’t match: the service account was recreated. Update the condition with the new UID.
Creating or updating the Provider returns 400 when Keycard can’t verify with a key, such as an RSA key under 2048 bits or a key that holds private key material. The error message names the first key it rejects.