Configure Azure Workload Identity
Authenticate Azure workloads to Keycard with a managed identity token.
An Azure workload gets a short-lived Microsoft Entra ID token for its managed identity. 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 your tenant’s public keys, then checks its audience and claims. This works on Azure VMs, App Service, Azure Functions, Container Apps, and other services with a managed identity.
Prerequisites
Section titled “Prerequisites”- Familiarity with the concepts in Workload Identity, and with Azure’s managed identities 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 managed identity attached to the workload, and its principal (object) ID:
az identity show --resource-group <resource-group> --name <identity-name> --query principalId -o tsvfor a user-assigned identity. The samples don’t name an identity, so they use the workload’s system-assigned identity when it has one. To use a user-assigned identity, pass its client ID when you request the token. - Permission to register applications in your Entra tenant, and your tenant ID
Register an Entra application for Keycard
Section titled “Register an Entra application for Keycard”Register an Entra application to act as Keycard’s audience, so no other service accepts these tokens, and set it to issue v2.0 tokens:
APP_ID=$(az ad app create --display-name "Keycard workload audience <zone-name>" --query appId -o tsv)az ad app update --id "$APP_ID" \ --identifier-uris "api://$APP_ID" \ --set api.requestedAccessTokenVersion=2az ad sp create --id "$APP_ID"$APP_ID is the app’s client ID. v2.0 tokens carry it as aud and are issued by https://login.microsoftonline.com/<tenant-id>/v2.0.
Register your tenant as a Provider
Section titled “Register your tenant as a Provider”Create one Provider per Entra tenant:
keycard agent api /zones/<zone-id>/providers --org <org-id> -X POST -d '{ "name": "Entra ID <tenant-id>", "identifier": "https://login.microsoftonline.com/<tenant-id>/v2.0", "protocols": { "oauth2": { "issuer": "https://login.microsoftonline.com/<tenant-id>/v2.0" } }}'Keycard discovers the tenant’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": "<entra-provider-id>","allowed_audience": "<app-client-id>","authentication_condition": "claims.oid == \"<managed-identity-principal-id>\""}'Field Value subjectOmitted. Entra can issue a different subfor the same identity in each application. Pinningoid, the identity’s object ID, is safer and works for managed identities.allowed_audienceThe Entra app’s client ID. Entra sets audto it, not to your Zone issuer URL.authentication_conditionPins the managed identity’s principal ID. oidis immutable and never reused.For every claim in an Entra access token, see Microsoft’s access token claims reference.
-
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”-
Set environment variables
Set these on the workload, for example in the App Service or Container Apps configuration:
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 a managed identity token and exchange it
Request a token for
api://<app-client-id>. Then send it asclient_assertion, with the credential’s Client ID asclient_id, in aclient_credentialsgrant:Terminal window pip install azure-identity keycardai-oauthimport osfrom azure.identity import ManagedIdentityCredentialfrom keycardai.oauth import Client, GrantTypeazure_token = ManagedIdentityCredential().get_token("api://<app-client-id>/.default").tokenwith Client(os.environ["KEYCARD_ISSUER"]) as client:response = client.client_credentials_grant(client_assertion=azure_token,client_assertion_type=GrantType.JWT_BEARER_CLIENT_ASSERTION,client_id=os.environ["KEYCARD_CLIENT_ID"],resource=os.environ["KEYCARD_RESOURCE_URL"],)access_token = response.access_tokenTerminal window npm install @azure/identity @keycardai/oauthimport { ManagedIdentityCredential } from "@azure/identity";import { ClientCredentialsClient } from "@keycardai/oauth";const { token: azureToken } = await new ManagedIdentityCredential().getToken("api://<app-client-id>/.default",);const client = new ClientCredentialsClient(process.env.KEYCARD_ISSUER!);const response = await client.requestToken({clientAssertion: azureToken,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/Azure/azure-sdk-for-go/sdk/azidentity github.com/keycardai/go-sdk/oauthcred, err := azidentity.NewManagedIdentityCredential(nil)if err != nil {return err}tok, err := cred.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{"api://<app-client-id>/.default"},})if err != nil {return err}azureToken := tok.Tokenclient := oauth.NewClientCredentialsClient(os.Getenv("KEYCARD_ISSUER"))response, err := client.RequestToken(ctx, oauth.ClientCredentialsRequest{ClientID: os.Getenv("KEYCARD_CLIENT_ID"),ClientAssertion: azureToken,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 "json"require "keycardai/oauth"require "net/http"# Azure VM instance metadata endpoint. Azure has no Ruby identity library.uri = URI("http://169.254.169.254/metadata/identity/oauth2/token")uri.query = URI.encode_www_form("api-version" => "2018-02-01", "resource" => "api://<app-client-id>")azure_token = JSON.parse(Net::HTTP.get(uri, { "Metadata" => "true" })).fetch("access_token")client = Keycardai::OAuth::ClientCredentialsClient.new(issuer: ENV.fetch("KEYCARD_ISSUER"))response = client.request_token(client_id: ENV.fetch("KEYCARD_CLIENT_ID"),client_assertion: azure_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 # Azure VM instance metadata endpointAZURE_TOKEN=$(curl -sSfG -H "Metadata: true" \-d api-version=2018-02-01 \--data-urlencode "resource=api://<app-client-id>" \"http://169.254.169.254/metadata/identity/oauth2/token" | jq -r .access_token)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=$AZURE_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 issuer, audience, 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 Provider and credential:
# On an Azure VM. Elsewhere, print the token your code requests.AZURE_TOKEN=$(curl -sSfG -H "Metadata: true" \ -d api-version=2018-02-01 \ --data-urlencode "resource=api://<app-client-id>" \ "http://169.254.169.254/metadata/identity/oauth2/token" | jq -r .access_token)echo "$AZURE_TOKEN" \ | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | {iss, aud, oid, ver}'veris1.0:issishttps://sts.windows.net/<tenant-id>/andaudisapi://<app-client-id>. Setapi.requestedAccessTokenVersionto2on the Entra app. A workload that already has a v1.0 token can keep getting it for up to 24 hours.oiddoesn’t match: the workload used a different identity, often the system-assigned identity instead of a user-assigned one. Pass the user-assigned identity’s client ID when requesting the token.AADSTS500011orAADSTS50001when requesting the token: the Entra app has no service principal in the tenant. Runaz ad sp create --id <app-client-id>.