SPB Git

Repository Public

kubernetes.md 14.1 KB 313 lines markdown

1---2title: Use WIF with Kubernetes3url: https://platform.claude.com/docs/en/manage-claude/wif-providers/kubernetes4description: Authenticate to the Claude API from self-managed Kubernetes clusters using projected service account tokens.5---67Self-managed Kubernetes clusters (kubeadm, k3s, OpenShift, and on-premises distributions) sign OIDC JSON Web Tokens (JWTs) for every pod through [projected service account tokens](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#serviceaccount-token-volume-projection). The cluster's API server acts as the OIDC issuer, and each token's `sub` claim follows the form `system:serviceaccount:<namespace>:<service-account>`. You can find your cluster's issuer URL by reading its discovery document:89```bash cURL10kubectl get --raw /.well-known/openid-configuration | jq -r .issuer11```1213<Note>14  The mechanism on this page (projected service-account token, cluster API server as the OIDC issuer) is native to Kubernetes itself, so it underlies every Kubernetes distribution. If you run on a managed Kubernetes service, the cloud provider guides walk through where to find the provider-managed issuer URL: [AWS (EKS)](https://platform.claude.com/docs/en/manage-claude/wif-providers/aws#use-eks-projected-service-account-tokens), [Google Cloud (GKE)](https://platform.claude.com/docs/en/manage-claude/wif-providers/gcp), or [Azure (AKS)](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure). If your cluster runs SPIRE, the SPIRE OIDC Discovery Provider is the issuer rather than the cluster API server; see [SPIFFE](https://platform.claude.com/docs/en/manage-claude/wif-providers/spiffe). For any other distribution or a managed provider not listed there, follow this guide and use the issuer URL your cluster reports.15</Note>1617## Prerequisites1819* Familiarity with [WIF concepts](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#concepts): service accounts, federation issuers, and federation rules.2021* A Kubernetes cluster with the [`--service-account-issuer`](https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/) flag configured on the API server. Most distributions set this by default; kubeadm clusters typically use `https://kubernetes.default.svc.cluster.local`. Your platform team can confirm the value if you don't have direct access to the API server configuration.2223* One of the following so Anthropic can validate token signatures:2425  * The issuer's JWKS endpoint is reachable from the public internet over HTTPS on port 443, or26  * You can fetch the JWKS from inside the cluster and register it in `inline` mode (covered in [Configure Anthropic](https://platform.claude.com/docs/en/manage-claude/wif-providers/kubernetes#configure-anthropic)).2728* Permission to create service accounts, federation issuers, and federation rules in the Claude Console for your Anthropic organization.2930## Configure Kubernetes3132Project a service account token into your pod with the audience and lifetime that your federation rule expects. The `serviceAccountToken` projection writes a fresh JWT to the mount path and rotates it before `expirationSeconds` elapses.3334```yaml Pod35apiVersion: v136kind: Pod37metadata:38  name: inference-worker39  namespace: inference40spec:41  serviceAccountName: inference-worker42  volumes:43    - name: anthropic-token44      projected:45        sources:46          - serviceAccountToken:47              audience: https://api.anthropic.com48              expirationSeconds: 360049              path: token50  containers:51    - name: app52      image: your-registry/inference-worker:latest53      env:54        - name: ANTHROPIC_IDENTITY_TOKEN_FILE55          value: /var/run/secrets/anthropic.com/token56        - name: ANTHROPIC_FEDERATION_RULE_ID57          value: fdrl_...58        - name: ANTHROPIC_ORGANIZATION_ID59          value: 00000000-0000-0000-0000-00000000000060        - name: ANTHROPIC_SERVICE_ACCOUNT_ID61          value: svac_...62        - name: ANTHROPIC_WORKSPACE_ID  # required when the rule covers multiple workspaces63          value: wrkspc_...64      volumeMounts:65        - name: anthropic-token66          mountPath: /var/run/secrets/anthropic.com67          readOnly: true68```6970The token issued for this pod carries `sub: "system:serviceaccount:inference:inference-worker"` and `aud: ["https://api.anthropic.com"]`.7172## Configure Anthropic7374In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select the **Kubernetes** tile. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.7576The wizard creates these resources for you. Use the following values whether you enter them in the wizard or send them to the [Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api):7778**Federation issuer:** Many self-managed clusters use an issuer URL such as `https://kubernetes.default.svc.cluster.local` that is not reachable from the public internet. If that applies to your cluster, choose the **inline** JWKS source and paste the cluster's keys. Fetch them from inside the cluster:7980```bash cURL81kubectl get --raw /openid/v1/jwks82```8384Then configure the issuer with the contents of the returned `keys` array (not the surrounding `{"keys": [...]}` wrapper):8586```json87{88  "name": "onprem-k8s",89  "issuer_url": "https://kubernetes.default.svc.cluster.local",90  "jwks": {91    "type": "inline",92    "keys": [{ "kty": "RSA", "kid": "...", "n": "...", "e": "AQAB" }]93  }94}95```9697In `inline` mode the `issuer_url` is only compared against the JWT's `iss` claim; Anthropic never attempts to reach it. If your issuer is publicly reachable, use `"jwks": {"type": "discovery"}` instead.9899<Warning>100  With `inline` keys you are responsible for updating the issuer when the cluster rotates its service account signing key. Rotation is rare (typically only during cluster upgrades), but token exchanges fail with a signature error until you push the new JWKS.101</Warning>102103**Federation rule:** Match the service account's `sub` claim and the audience you set on the projected token.104105```json106{107  "name": "onprem-inference",108  "issuer_id": "fdis_...",109  "match": {110    "subject_prefix": "system:serviceaccount:inference:inference-worker",111    "audience": "https://api.anthropic.com"112  },113  "target": {114    "type": "service_account",115    "service_account_id": "svac_..."116  },117  "workspace_id": "wrkspc_...",118  "oauth_scope": "workspace:developer",119  "token_lifetime_seconds": 600120}121```122123Be as specific as the workload allows. Loosen `subject_prefix` to `system:serviceaccount:inference:*` (the trailing `*` makes it a prefix match) only if every service account in the namespace should map to the same Anthropic service account. Add the rule's `fdrl_...` ID to your pod's `ANTHROPIC_FEDERATION_RULE_ID` environment variable.124125## Acquire and use the token126127The pod spec in [Configure Kubernetes](https://platform.claude.com/docs/en/manage-claude/wif-providers/kubernetes#configure-kubernetes) sets `ANTHROPIC_IDENTITY_TOKEN_FILE` to the projected mount path, along with `ANTHROPIC_FEDERATION_RULE_ID`, `ANTHROPIC_ORGANIZATION_ID`, `ANTHROPIC_SERVICE_ACCOUNT_ID`, and `ANTHROPIC_WORKSPACE_ID`. With those in place, the SDK reads the token from disk on every exchange and refreshes the Anthropic access token automatically.128129<CodeGroup>130  ```bash cURL131  JWT=$(cat "$ANTHROPIC_IDENTITY_TOKEN_FILE")132133  ACCESS_TOKEN=$(curl -sS https://api.anthropic.com/v1/oauth/token \134    -H "content-type: application/json" \135    --data @- <<JSON | jq -r .access_token136  {137    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",138    "assertion": "$JWT",139    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",140    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",141    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",142    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"143  }144  JSON145  )146147  curl https://api.anthropic.com/v1/messages \148    -H "authorization: Bearer $ACCESS_TOKEN" \149    -H "anthropic-version: 2023-06-01" \150    -H "content-type: application/json" \151    -d '{152      "model": "claude-opus-5",153      "max_tokens": 1024,154      "messages": [{"role": "user", "content": "Hello, Claude"}]155    }' | jq -r '.content[] | select(.type == "text") | .text'156  ```157158  ```python Python159  import anthropic160161  # Reads ANTHROPIC_IDENTITY_TOKEN_FILE, ANTHROPIC_FEDERATION_RULE_ID,162  # ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID163  # from the pod's environment.164  client = anthropic.Anthropic()165166  message = client.messages.create(167      model="claude-opus-5",168      max_tokens=1024,169      messages=[{"role": "user", "content": "Hello, Claude"}],170  )171  print(next(block.text for block in message.content if block.type == "text"))172  ```173174  ```typescript TypeScript175  import Anthropic from "@anthropic-ai/sdk";176177  // Reads ANTHROPIC_IDENTITY_TOKEN_FILE, ANTHROPIC_FEDERATION_RULE_ID,178  // ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID179  // from the pod's environment.180  const client = new Anthropic();181182  const message = await client.messages.create({183    model: "claude-opus-5",184    max_tokens: 1024,185    messages: [{ role: "user", content: "Hello, Claude" }]186  });187  for (const block of message.content) {188    if (block.type === "text") {189      console.log(block.text);190    }191  }192  ```193194  ```go Go195  // Reads ANTHROPIC_IDENTITY_TOKEN_FILE, ANTHROPIC_FEDERATION_RULE_ID,196  // ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID197  // from the pod's environment.198  client := anthropic.NewClient()199200  message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{201  	Model:     anthropic.ModelClaudeOpus5,202  	MaxTokens: 1024,203  	Messages: []anthropic.MessageParam{204  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),205  	},206  })207  if err != nil {208  	panic(err)209  }210  for _, block := range message.Content {211  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {212  		fmt.Println(textBlock.Text)213  		break214  	}215  }216  ```217218  ```java Java219  AnthropicClient client = AnthropicOkHttpClient.fromEnv();220221  var message = client.messages().create(MessageCreateParams.builder()222          .model(Model.CLAUDE_OPUS_5)223          .maxTokens(1024)224          .addUserMessage("Hello, Claude")225          .build());226227  IO.println(message.content());228  ```229230  ```csharp C#231  // Reads ANTHROPIC_IDENTITY_TOKEN_FILE, ANTHROPIC_FEDERATION_RULE_ID,232  // ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID233  // from the pod's environment.234  using var client = new AnthropicClient();235236  var message = await client.Messages.Create(new()237  {238      Model = Model.ClaudeOpus5,239      MaxTokens = 1024,240      Messages = [new() { Role = Role.User, Content = "Hello, Claude" }],241  });242  foreach (var block in message.Content)243  {244      if (block.Value is TextBlock textBlock)245      {246          Console.WriteLine(textBlock.Text);247      }248  }249  ```250251  ```bash CLI252  # Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,253  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE254  ant messages create \255    --model claude-opus-5 \256    --max-tokens 1024 \257    --message '{role: user, content: "Hello, Claude"}'258  ```259260  ```php PHP261  use Anthropic\Client;262263  // Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,264  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE265  $client = new Client();266267  $message = $client->messages->create(268      model: 'claude-opus-5',269      maxTokens: 1024,270      messages: [['role' => 'user', 'content' => 'Hello, Claude']],271  );272  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');273  echo $textBlock->text, PHP_EOL;274  ```275276  ```ruby Ruby277  require "anthropic"278279  # Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,280  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE281  client = Anthropic::Client.new282283  message = client.messages.create(284    model: "claude-opus-5",285    max_tokens: 1024,286    messages: [{role: "user", content: "Hello, Claude"}]287  )288  puts message.content.find { it.type == :text }.text289  ```290</CodeGroup>291292## Verify the setup293294A successful exchange returns an `access_token` beginning with `sk-ant-oat01-` and an `expires_in` value in seconds. If the exchange fails with the opaque `401` `authentication_error` response (message `Authentication failed`), check the [authentication history page](https://platform.claude.com/settings/workload-identity-federation?tab=history) for the deny reason and see [Troubleshoot a failed exchange](https://platform.claude.com/docs/en/manage-claude/wif-reference#troubleshoot-a-failed-exchange); the most common Kubernetes-side cause is a JWKS key mismatch (for `inline` mode, re-fetch with `kubectl get --raw /openid/v1/jwks` and update the issuer).295296## Scope your rule297298<Warning>299  A `subject_prefix` of `system:serviceaccount:*` matches every service account in the cluster, so any pod can obtain a federated Anthropic token. Without an `audience` matcher, the rule also matches the cluster's default-audience tokens, which every pod already has projected.300</Warning>301302Lock the rule's `match` block to the narrowest scope that fits your use case:303304* **Pin namespace and service-account name:** Use the full `system:serviceaccount:<namespace>:<name>` value with no trailing `*`.305* **Always set an audience:** Require `audience` on the rule and set the same value on the pod's `serviceAccountToken` projection so default-audience tokens are rejected.306* **Use a separate rule per namespace:** Create a distinct rule and Anthropic service account for each namespace rather than widening one rule.307* **Scope inline-JWKS issuers to one cluster:** When several clusters share an issuer URL, register each cluster's JWKS as its own federation issuer and bind rules to that issuer only.308309## Next steps310311* [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation): concepts, the token-exchange flow, and SDK configuration options.312* [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference): environment variables, JWKS source modes, and rule match modes.313
Files main
Menu

Theme