Workload Identity
Authenticate workloads to Keycard with platform-issued identity tokens, without any long-lived secrets.
Workloads running on a cloud or CI platform can authenticate to Keycard with the identity token their platform already issues them, without any long-lived secrets. The workload presents that token as a client assertion and names the Application credential it authenticates as with client_id.
How it works
Section titled “How it works”- The platform issues a token. The workload requests a short-lived JWT from its platform, with your Zone issuer URL as the audience. If the platform sets the audience itself, set the credential’s allowed audience to that value.
- The workload calls the token endpoint. It sends a standard OAuth request to
/oauth/2/tokenwithclient_assertionset to the platform token andclient_idset to the credential ID. - Keycard validates the token. Keycard looks up the credential by
client_id, verifies the token’s signature, issuer, and expiry against the credential’s Provider, then checks the audience, subject, and authentication condition. Any failure returnsinvalid_client, and the Audit Log records details on the failure. - Keycard issues a token. The workload receives a token for its Application. The
client_credentialsgrant returns a token for the Application itself. Theauthorization_codegrant uses the same client authentication to return tokens on behalf of a User.
The credential’s Client ID is an identifier, not a secret. Store it alongside other configuration as KEYCARD_CLIENT_ID.
Provider
Section titled “Provider”The Provider represents the platform that issues the workload’s tokens. It specifies the issuer and where Keycard gets the keys that verify the token’s signature, read from the first of these that’s set:
- Stored keys: a key set stored on the Provider, for issuers Keycard can’t reach, such as a private Kubernetes cluster.
- Key set URL: a URL Keycard fetches the key set from.
- Discovery: the key set URL in the issuer’s
<issuer-url>/.well-known/openid-configurationdocument.
Most platforms publish a discovery document, so their Provider sets only issuer. Create it with the Keycard CLI:
keycard agent api /zones/<zone-id>/providers --org <org-id> -X POST -d '{ "name": "<provider-name>", "identifier": "<issuer-url>", "protocols": { "oauth2": { "issuer": "<issuer-url>" } }}'See the API Reference for the jwks and jwks_uri fields.
Application credential fields
Section titled “Application credential fields”A token credential belongs to one Application and trusts one Provider. Create it with the Keycard CLI:
keycard agent api /zones/<zone-id>/application-credentials --org <org-id> -X POST -d '{ "type": "token", "version": 2, "application_id": "<application-id>", "provider_id": "<provider-id>", "subject": "<subject>", "allowed_audience": "<audience>", "authentication_condition": "<cel-expression>"}'| Field | Validation |
|---|---|
subject |
The token’s sub must match exactly. A trailing * matches every sub that starts with the text before it, for example repo:<org>/*. |
allowed_audience |
The token’s aud must be exactly this one value. Defaults to the Zone issuer URL. |
authentication_condition |
A CEL expression over the token’s claims. It must evaluate to true. A missing claim or evaluation error denies the request. |
Set subject, authentication_condition, or both. Several credentials can trust the same subject, because the workload names its credential with client_id.
Authentication conditions
Section titled “Authentication conditions”authentication_condition is a CEL expression over the token’s verified claims, available as claims. Reference a claim as claims.<claim-key>:
| Check | Expression |
|---|---|
| Claim equals a value | claims.<claim-key> == "<claim-value>" |
| All of several claims | claims.<claim-key> == "<claim-value>" && claims.<other-claim-key> == "<other-value>" |
| Claim is one of a set | claims.<claim-key> in ["<value-1>", "<value-2>"] |
Claim starts with a prefix ending at a segment boundary such as : or / |
claims.<claim-key>.startsWith("<prefix>/") |
| Array claim contains a value | "<claim-value>" in claims.<claim-key> |
| Nested claim | claims.<parent-key>.<child-key> == "<claim-value>" |
Key with -, :, or . |
claims["<claim-key>"] == "<claim-value>" |
Match the claim’s JSON type: quote strings, leave numbers and booleans unquoted. Reading a claim the token doesn’t have denies the request. To make a claim optional, guard it: !has(claims.<claim-key>) || claims.<claim-key> == "<claim-value>". For a key with -, :, or ., guard with !("<claim-key>" in claims) instead, because has() takes only the dot form.
Authenticate a workload
Section titled “Authenticate a workload”A workload signs in to Keycard with the short-lived token its platform gives it, without any long-lived secrets. Keycard checks that token against the Workload Identity credential, then issues a token.
In code, give the SDK two things:
- The platform token, or where to read it, such as a file or the cloud’s metadata server.
- The credential’s Client ID, from
KEYCARD_CLIENT_ID.
The SDK sends both with each token request. This works for each way an Application gets a token:
| To do this | Flow |
|---|---|
| Get a token for the Application itself | Client credentials |
| Sign a User in through the browser | Authorization code |
| Sign a User in on another device, such as a CLI | Device code |
| Trade a token you hold for a token to a Resource | Token exchange |
The examples below show each flow. The exact call differs by SDK and version.
Without an SDK
Add these parameters to the token request (RFC 7523):
| Parameter | Value |
|---|---|
client_assertion |
The platform token |
client_assertion_type |
urn:ietf:params:oauth:client-assertion-type:jwt-bearer |
client_id |
The credential’s Client ID |
Client credentials
Section titled “Client credentials”import asyncioimport os
from keycardai.oauth import AsyncClient, GrantTypefrom keycardai.oauth.server import FileTokenSource
token_source = FileTokenSource(token_file_path="<token-file-path>")
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_token
access_token = asyncio.run(get_access_token())import { ClientCredentialsClient } from "@keycardai/oauth";import { FileTokenSource } from "@keycardai/oauth/server";
const tokenSource = new FileTokenSource({ tokenFilePath: "<token-file-path>" });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;tokenSource, err := oauth.NewFileTokenSource( oauth.WithFileTokenPath("<token-file-path>"),)if err != nil { return err}
platformToken, 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: platformToken, ClientAssertionType: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", Resource: os.Getenv("KEYCARD_RESOURCE_URL"),})if err != nil { return err}
accessToken := response.AccessTokenrequire "keycardai/oauth"
platform_token = Keycardai::OAuth::FileTokenSource.new( token_file_path: "<token-file-path>").identity_token
client = Keycardai::OAuth::ClientCredentialsClient.new(issuer: ENV.fetch("KEYCARD_ISSUER"))
response = client.request_token( client_id: ENV.fetch("KEYCARD_CLIENT_ID"), client_assertion: platform_token, client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", resource: ENV.fetch("KEYCARD_RESOURCE_URL"))access_token = response.access_tokencurl -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 <token-file-path>)" \ --data-urlencode "client_id=$KEYCARD_CLIENT_ID" \ --data-urlencode "resource=$KEYCARD_RESOURCE_URL"Authorization code
Section titled “Authorization code”Pass a Workload Identity credential to the code exchange. Without any long-lived secrets, it sends the client assertion and credential ID. The code is bound to the client_id in the authorize URL, so use the credential ID there too.
import os
from keycardai.oauth import AsyncClientfrom keycardai.oauth.server import FileTokenSource, WorkloadIdentity
credential = WorkloadIdentity( FileTokenSource(token_file_path="<token-file-path>"), client_id=os.environ["KEYCARD_CLIENT_ID"],)
async with AsyncClient(os.environ["KEYCARD_ISSUER"]) as client: tokens = await client.exchange_authorization_code( code=code, code_verifier=code_verifier, redirect_uri="<redirect-uri>", credential=credential, )import { exchangeAuthorizationCode } from "@keycardai/oauth/pkce";import { FileTokenSource, WorkloadIdentity } from "@keycardai/oauth/server";
const credential = new WorkloadIdentity(new FileTokenSource({ tokenFilePath: "<token-file-path>" }), { clientId: process.env.KEYCARD_CLIENT_ID!,});
const tokens = await exchangeAuthorizationCode(process.env.KEYCARD_ISSUER!, code, { codeVerifier, redirectUri: "<redirect-uri>", credential,});source, err := oauth.NewFileTokenSource(oauth.WithFileTokenPath("<token-file-path>"))if err != nil { return err}credential, err := oauth.NewWorkloadIdentity(source, oauth.WithWorkloadClientID(os.Getenv("KEYCARD_CLIENT_ID")))if err != nil { return err}
tokens, err := oauth.ExchangeAuthorizationCode(ctx, os.Getenv("KEYCARD_ISSUER"), oauth.AuthorizationCodeExchangeRequest{ Code: code, CodeVerifier: codeVerifier, RedirectURI: "<redirect-uri>", Credential: credential, })require "keycardai/oauth"
credential = Keycardai::OAuth::WorkloadIdentity.new( source: Keycardai::OAuth::FileTokenSource.new(token_file_path: "<token-file-path>"), client_id: ENV.fetch("KEYCARD_CLIENT_ID"))
tokens = Keycardai::OAuth.exchange_authorization_code( ENV.fetch("KEYCARD_ISSUER"), code: code, code_verifier: code_verifier, redirect_uri: "<redirect-uri>", credential: credential)curl -X POST "$KEYCARD_ISSUER/oauth/2/token" \ -d grant_type=authorization_code \ -d code="<code>" \ -d code_verifier="<code-verifier>" \ --data-urlencode redirect_uri="<redirect-uri>" \ -d client_id="$KEYCARD_CLIENT_ID" \ --data-urlencode client_assertion="<platform-token>" \ --data-urlencode client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer