SPB Git

Repository Public

aws.md 31.8 KB 814 lines markdown

1---2title: Use WIF with AWS3url: https://platform.claude.com/docs/en/manage-claude/wif-providers/aws4description: Authenticate AWS workloads on Lambda, EC2, ECS, or EKS to the Claude API with Workload Identity Federation and STS-issued identity tokens.5---67AWS workloads can authenticate to the Claude API without static API keys by exchanging an AWS-signed OIDC identity token. The recommended path calls the AWS STS [`GetWebIdentityToken`](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html) API, which works anywhere the workload has AWS credentials: Lambda, EC2, ECS, and EKS. EKS workloads can alternatively use the [Kubernetes projected-token path](https://platform.claude.com/docs/en/manage-claude/wif-providers/aws#use-eks-projected-service-account-tokens), which has fewer configuration steps but only works inside a pod.89This guide shows both paths. For the underlying concepts (service accounts, federation issuers, and federation rules), see [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation).1011## Prerequisites1213* Familiarity with [WIF concepts](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#concepts): service accounts, federation issuers, and federation rules.14* An AWS workload (EKS pod, ECS task, Lambda function, or EC2 instance) with an attached IAM role.15* The `aws` CLI or an AWS SDK available in the workload.16* Permission to create service accounts, federation issuers, and federation rules in the Claude Console for your Anthropic organization.1718## Use STS web identity tokens (recommended)1920The AWS STS `GetWebIdentityToken` API returns an OIDC token signed by AWS that asserts the caller's IAM identity. Because it uses the workload's ambient AWS credentials, the same integration covers Lambda, EC2, ECS, and EKS.2122### Configure AWS2324<Steps>25  <Step title="Enable outbound web identity federation for the account">26    This is an account-level flag, off by default. In the AWS console, open **IAM**, choose **Account settings**, and enable **Outbound web identity federation**. To enable it programmatically:2728    ```bash29    python3 -c "import boto3; boto3.client('iam').enable_outbound_web_identity_federation()"30    ```3132    If this is not enabled, calls to `GetWebIdentityToken` fail with `OutboundWebIdentityFederationDisabledException`.33  </Step>3435  <Step title="Grant the workload's IAM role permission to call the API">36    Attach this policy to the IAM role that your Lambda function, EC2 instance, or ECS task runs as:3738    ```json39    {40      "Version": "2012-10-17",41      "Statement": [42        {43          "Effect": "Allow",44          "Action": ["sts:GetWebIdentityToken"],45          "Resource": "*"46        }47      ]48    }49    ```50  </Step>5152  <Step title="Find your account's STS issuer URL">53    After enabling outbound federation, the **IAM > Account settings** page shows a **Get Token Issuer URL** field with a value of the form `https://<uuid>.tokens.sts.global.api.aws`. This URL is unique to your AWS account; copy it for the next step. To retrieve it programmatically:5455    ```bash56    python3 -c "import boto3; print(boto3.client('iam').get_outbound_web_identity_federation_info())"57    ```58  </Step>59</Steps>6061### Configure Anthropic6263In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select the **AWS** tile. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.6465The 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):6667**Federation issuer:** Register the per-account STS issuer URL you copied in the prior step. It exposes a public JWKS endpoint, so use discovery mode.6869```json70{71  "name": "aws-sts",72  "issuer_url": "https://<uuid>.tokens.sts.global.api.aws",73  "jwks": { "type": "discovery" }74}75```7677**Federation rule:** Match the audience you pass to `GetWebIdentityToken` and the calling role's IAM role ARN in the `sub` claim. The `sub` value is the IAM role ARN of the workload that called the API, in the form `arn:aws:iam::<account>:role/<role-name>`. The token also carries an `https://sts.amazonaws.com/` claim with `aws_account`, `org_id`, `principal_id`, and any `request_tags` you passed; you can match on those with the rule's `claims` map or a CEL `condition` for finer control.7879```json80{81  "name": "prod-inference",82  "issuer_id": "fdis_...",83  "match": {84    "subject_prefix": "arn:aws:iam::123456789012:role/inference-worker",85    "audience": "https://api.anthropic.com"86  },87  "target": { "type": "service_account", "service_account_id": "svac_..." },88  "workspace_id": "wrkspc_...",89  "oauth_scope": "workspace:developer",90  "token_lifetime_seconds": 60091}92```9394Be as specific as the workload allows. Match the exact role ARN, and only broaden `subject_prefix` (for example, to `arn:aws:iam::123456789012:role/*`) if multiple IAM roles should map to the same Anthropic service account.9596### Acquire and use the token9798Call `GetWebIdentityToken` with `https://api.anthropic.com` as the audience, then pass the result to the SDK's federation credentials. The token provider is a callable, so the SDK re-invokes STS on each refresh.99100<Note>101  `GetWebIdentityToken` is available only on regional STS endpoints. If you receive `'STS' object has no attribute 'get_web_identity_token'` or a similar error, pin your STS client to a region (for example, `boto3.client("sts", region_name="us-east-1")`) and ensure your AWS SDK is recent enough to include the API.102</Note>103104<CodeGroup>105  ```bash cURL106  JWT=$(aws sts get-web-identity-token \107    --region us-east-1 \108    --audience "https://api.anthropic.com" \109    --signing-algorithm RS256 \110    --duration-seconds 900 \111    --query WebIdentityToken --output text)112113  RESPONSE=$(curl -sS https://api.anthropic.com/v1/oauth/token \114    -H "content-type: application/json" \115    --data @- <<JSON116  {117    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",118    "assertion": "$JWT",119    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",120    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",121    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",122    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"123  }124  JSON125  )126127  ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r .access_token)128129  curl https://api.anthropic.com/v1/messages \130    -H "authorization: Bearer $ACCESS_TOKEN" \131    -H "anthropic-version: 2023-06-01" \132    -H "content-type: application/json" \133    -d '{134      "model": "claude-opus-5",135      "max_tokens": 1024,136      "messages": [{"role": "user", "content": "Hello from AWS"}]137    }' | jq -r '.content[] | select(.type == "text") | .text'138  ```139140  ```python Python141  import os142143  import anthropic144  import boto3145  from anthropic import WorkloadIdentityCredentials146147148  def get_sts_web_identity_token() -> str:149      sts = boto3.client("sts", region_name="us-east-1")150      resp = sts.get_web_identity_token(151          Audience=["https://api.anthropic.com"],152          SigningAlgorithm="RS256",153          DurationSeconds=900,154      )155      return resp["WebIdentityToken"]156157158  client = anthropic.Anthropic(159      credentials=WorkloadIdentityCredentials(160          identity_token_provider=get_sts_web_identity_token,161          federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],162          organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],163          service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],164          workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),165      ),166  )167168  message = client.messages.create(169      model="claude-opus-5",170      max_tokens=1024,171      messages=[{"role": "user", "content": "Hello from AWS"}],172  )173  print(next(block.text for block in message.content if block.type == "text"))174  ```175176  ```typescript TypeScript177  import Anthropic from "@anthropic-ai/sdk";178  import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";179  import { STSClient, GetWebIdentityTokenCommand } from "@aws-sdk/client-sts";180181  const sts = new STSClient({ region: "us-east-1" });182183  async function getStsWebIdentityToken(): Promise<string> {184    const out = await sts.send(185      new GetWebIdentityTokenCommand({186        Audience: ["https://api.anthropic.com"],187        SigningAlgorithm: "RS256",188        DurationSeconds: 900189      })190    );191    return out.WebIdentityToken!;192  }193194  const client = new Anthropic({195    credentials: oidcFederationProvider({196      identityTokenProvider: getStsWebIdentityToken,197      federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,198      organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,199      serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,200      workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,201      baseURL: "https://api.anthropic.com",202      fetch203    })204  });205206  const message = await client.messages.create({207    model: "claude-opus-5",208    max_tokens: 1024,209    messages: [{ role: "user", content: "Hello from AWS" }]210  });211  for (const block of message.content) {212    if (block.type === "text") {213      console.log(block.text);214    }215  }216  ```217218  ```go Go219  ctx := context.TODO()220  cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-east-1"))221  if err != nil {222  	panic(err)223  }224  stsClient := sts.NewFromConfig(cfg)225226  getStsToken := option.IdentityTokenFunc(func(ctx context.Context) (string, error) {227  	out, err := stsClient.GetWebIdentityToken(ctx, &sts.GetWebIdentityTokenInput{228  		Audience:         []string{"https://api.anthropic.com"},229  		SigningAlgorithm: "RS256",230  		DurationSeconds:  aws.Int32(900),231  	})232  	if err != nil {233  		return "", err234  	}235  	return *out.WebIdentityToken, nil236  })237238  client := anthropic.NewClient(239  	option.WithFederationTokenProvider(getStsToken, option.FederationOptions{240  		FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),241  		OrganizationID:   os.Getenv("ANTHROPIC_ORGANIZATION_ID"),242  		ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),243  		WorkspaceID:      os.Getenv("ANTHROPIC_WORKSPACE_ID"),244  	}),245  )246247  message, err := client.Messages.New(ctx, anthropic.MessageNewParams{248  	Model:     anthropic.ModelClaudeOpus5,249  	MaxTokens: 1024,250  	Messages: []anthropic.MessageParam{251  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from AWS")),252  	},253  })254  if err != nil {255  	panic(err)256  }257  for _, block := range message.Content {258  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {259  		fmt.Println(textBlock.Text)260  		break261  	}262  }263  ```264265  ```java Java266  StsClient sts = StsClient.builder().region(Region.US_EAST_1).build();267268  IdentityTokenProvider getStsToken = () -> sts.getWebIdentityToken(269                  GetWebIdentityTokenRequest.builder()270                          .audience("https://api.anthropic.com")271                          .signingAlgorithm("RS256")272                          .durationSeconds(900)273                          .build())274          .webIdentityToken();275276  AnthropicClient client = AnthropicOkHttpClient.builder()277          .federationTokenProvider(278                  getStsToken,279                  System.getenv("ANTHROPIC_FEDERATION_RULE_ID"),280                  System.getenv("ANTHROPIC_ORGANIZATION_ID"),281                  System.getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"))282          .build();283284  var message = client.messages().create(MessageCreateParams.builder()285          .model(Model.CLAUDE_OPUS_5)286          .maxTokens(1024)287          .addUserMessage("Hello from AWS")288          .build());289290  IO.println(message.content());291  ```292293  ```csharp C#294  using Amazon.SecurityToken;295  using Amazon.SecurityToken.Model;296  // ...297  using Anthropic.Credentials;298  // ...299300  var credentials = new WorkloadIdentityCredentials(new WorkloadIdentityOptions301  {302      FederationRuleId = Environment.GetEnvironmentVariable("ANTHROPIC_FEDERATION_RULE_ID")!,303      OrganizationId = Environment.GetEnvironmentVariable("ANTHROPIC_ORGANIZATION_ID"),304      ServiceAccountId = Environment.GetEnvironmentVariable("ANTHROPIC_SERVICE_ACCOUNT_ID"),305      WorkspaceId = Environment.GetEnvironmentVariable("ANTHROPIC_WORKSPACE_ID"),306      IdentityTokenProvider = new StsTokenProvider(),307  });308  using var client = new AnthropicClient(new ClientOptions { Credentials = credentials });309310  var message = await client.Messages.Create(new()311  {312      Model = Model.ClaudeOpus5,313      MaxTokens = 1024,314      Messages = [new() { Role = Role.User, Content = "Hello from AWS" }],315  });316  foreach (var block in message.Content)317  {318      if (block.Value is TextBlock textBlock)319      {320          Console.WriteLine(textBlock.Text);321      }322  }323324  class StsTokenProvider : IIdentityTokenProvider325  {326      private readonly AmazonSecurityTokenServiceClient _sts = new(Amazon.RegionEndpoint.USEast1);327328      public async Task<string> GetIdentityTokenAsync(CancellationToken ct = default)329      {330          var resp = await _sts.GetWebIdentityTokenAsync(new GetWebIdentityTokenRequest331          {332              Audience = ["https://api.anthropic.com"],333              SigningAlgorithm = "RS256",334              DurationSeconds = 900,335          }, ct);336          return resp.WebIdentityToken;337      }338  }339  ```340341  ```bash CLI342  TOKEN_FILE=$(mktemp)343  aws sts get-web-identity-token \344    --region us-east-1 \345    --audience "https://api.anthropic.com" \346    --signing-algorithm RS256 \347    --duration-seconds 900 \348    --query WebIdentityToken --output text > "$TOKEN_FILE"349350  export ANTHROPIC_IDENTITY_TOKEN_FILE="$TOKEN_FILE"351  # ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID, and352  # ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID are read from the environment353  ant messages create \354    --model claude-opus-5 \355    --max-tokens 1024 \356    --message '{role: user, content: "Hello from AWS"}'357  ```358359  ```php PHP360  use Anthropic\Client;361  use Anthropic\Credentials\WorkloadIdentityCredentials;362  use Aws\Sts\StsClient;363364  $sts = new StsClient(['region' => 'us-east-1', 'version' => 'latest']);365  $client = new Client(credentials: new WorkloadIdentityCredentials(366      identityTokenProvider: fn() => $sts->getWebIdentityToken([367          'Audience' => ['https://api.anthropic.com'],368          'SigningAlgorithm' => 'RS256',369          'DurationSeconds' => 900,370      ])['WebIdentityToken'],371      federationRuleId: getenv('ANTHROPIC_FEDERATION_RULE_ID'),372      organizationId: getenv('ANTHROPIC_ORGANIZATION_ID'),373      serviceAccountId: getenv('ANTHROPIC_SERVICE_ACCOUNT_ID'),374      workspaceId: getenv('ANTHROPIC_WORKSPACE_ID') ?: null,375  ));376377  $message = $client->messages->create(378      model: 'claude-opus-5',379      maxTokens: 1024,380      messages: [['role' => 'user', 'content' => 'Hello from AWS']],381  );382  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');383  echo $textBlock->text, PHP_EOL;384  ```385386  ```ruby Ruby387  require "anthropic"388  require "aws-sdk-sts"389390  sts = Aws::STS::Client.new(region: "us-east-1")391  client = Anthropic::Client.new(392    credentials: Anthropic::WorkloadIdentityCredentials.new(393      identity_token_provider: -> {394        sts.get_web_identity_token(395          audience: ["https://api.anthropic.com"],396          signing_algorithm: "RS256",397          duration_seconds: 900,398        ).web_identity_token399      },400      federation_rule_id: ENV.fetch("ANTHROPIC_FEDERATION_RULE_ID"),401      organization_id: ENV.fetch("ANTHROPIC_ORGANIZATION_ID"),402      service_account_id: ENV.fetch("ANTHROPIC_SERVICE_ACCOUNT_ID"),403      workspace_id: ENV["ANTHROPIC_WORKSPACE_ID"],404    ),405  )406407  message = client.messages.create(408    model: "claude-opus-5",409    max_tokens: 1024,410    messages: [{role: "user", content: "Hello from AWS"}]411  )412  puts message.content.find { it.type == :text }.text413  ```414</CodeGroup>415416### Verify the setup417418From inside the workload, exchange an STS-issued token directly and inspect the response:419420```bash cURL421JWT=$(aws sts get-web-identity-token \422  --region us-east-1 \423  --audience "https://api.anthropic.com" \424  --signing-algorithm RS256 \425  --duration-seconds 900 \426  --query WebIdentityToken --output text)427428curl -sS https://api.anthropic.com/v1/oauth/token \429  -H "content-type: application/json" \430  -d "{431    \"grant_type\": \"urn:ietf:params:oauth:grant-type:jwt-bearer\",432    \"assertion\": \"$JWT\",433    \"federation_rule_id\": \"fdrl_...\",434    \"organization_id\": \"00000000-0000-0000-0000-000000000000\",435    \"service_account_id\": \"svac_...\",436    \"workspace_id\": \"wrkspc_...\"437  }" | jq438```439440A 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 AWS-side cause is an `iss` mismatch (the per-account STS issuer URL must match the registered `issuer_url` exactly).441442## Use EKS projected service-account tokens443444If your workload runs in an EKS pod, you can skip the STS call and read a Kubernetes-projected service-account token directly from disk. Kubernetes natively projects an OIDC-compatible token into the pod, and the SDK can read it from a file path, so no token-provider callable is required. This path has two fewer AWS configuration steps than the STS path but only works inside a pod; the underlying mechanism is the same as the [generic Kubernetes integration](https://platform.claude.com/docs/en/manage-claude/wif-providers/kubernetes).445446This path additionally requires an EKS cluster with an [IAM OIDC provider enabled](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html) and `kubectl` access to the cluster.447448### Configure your EKS cluster449450<Steps>451  <Step title="Find your cluster's OIDC issuer URL">452    Each EKS cluster has a unique OIDC issuer. Retrieve it with the AWS CLI:453454    ```bash CLI455    aws eks describe-cluster \456      --name <cluster-name> \457      --query "cluster.identity.oidc.issuer" \458      --output text459    ```460461    The output looks like `https://oidc.eks.us-west-2.amazonaws.com/id/6FA42E7BFDE8549CB...`. You'll register this URL as a federation issuer in the next section.462  </Step>463464  <Step title="Create the service account and project an Anthropic-audience token">465    The EKS pod identity webhook detects the `eks.amazonaws.com/role-arn` annotation and automatically projects a token with `aud: sts.amazonaws.com`, exposing its path as `AWS_WEB_IDENTITY_TOKEN_FILE`. That token is for AWS role assumption. For the Anthropic exchange, project a second token with `audience: https://api.anthropic.com` and mount it at a dedicated path.466467    ```yaml468    apiVersion: v1469    kind: ServiceAccount470    metadata:471      name: inference-worker472      namespace: inference473      annotations:474        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/inference-worker475    ```476477    ```yaml478    apiVersion: v1479    kind: Pod480    metadata:481      name: inference-worker482      namespace: inference483    spec:484      serviceAccountName: inference-worker485      volumes:486        - name: anthropic-token487          projected:488            sources:489              - serviceAccountToken:490                  audience: https://api.anthropic.com491                  expirationSeconds: 3600492                  path: token493      containers:494        - name: app495          image: your-registry/inference-worker:latest496          env:497            - name: ANTHROPIC_IDENTITY_TOKEN_FILE498              value: /var/run/secrets/anthropic.com/token499            - name: ANTHROPIC_FEDERATION_RULE_ID500              value: fdrl_...501            - name: ANTHROPIC_ORGANIZATION_ID502              value: 00000000-0000-0000-0000-000000000000503            - name: ANTHROPIC_SERVICE_ACCOUNT_ID504              value: svac_...505            - name: ANTHROPIC_WORKSPACE_ID  # required when the rule covers multiple workspaces506              value: wrkspc_...507          volumeMounts:508            - name: anthropic-token509              mountPath: /var/run/secrets/anthropic.com510              readOnly: true511    ```512  </Step>513514  <Step title="Note the token's claim shape">515    The projected token is a JSON Web Token (JWT) signed by your cluster's OIDC issuer. Its `sub` claim follows the Kubernetes convention `system:serviceaccount:<namespace>:<service-account-name>`:516517    ```json518    {519      "iss": "https://oidc.eks.us-west-2.amazonaws.com/id/6FA42E7BFDE8549CB...",520      "sub": "system:serviceaccount:inference:inference-worker",521      "aud": ["https://api.anthropic.com"],522      "kubernetes.io": {523        "namespace": "inference",524        "serviceaccount": { "name": "inference-worker", "uid": "..." }525      },526      "exp": 1775527120,527      "iat": 1775523520528    }529    ```530531    The `serviceAccountToken` projection sets `aud` to `https://api.anthropic.com`. The separate IRSA-injected token at `AWS_WEB_IDENTITY_TOKEN_FILE` carries `aud: sts.amazonaws.com` and is for AWS API calls, not this exchange.532  </Step>533</Steps>534535### Configure Anthropic536537In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select the **AWS** tile. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.538539The 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):540541**Federation issuer:** EKS issuers expose a public JWKS endpoint, so use discovery mode. The issuer URL must exactly match the token's `iss` claim. Register one issuer per cluster.542543```json544{545  "name": "prod-eks-uswest2",546  "issuer_url": "https://oidc.eks.us-west-2.amazonaws.com/id/6FA42E7BFDE8549CB...",547  "jwks": { "type": "discovery" }548}549```550551**Federation rule:** Match the Kubernetes `sub` claim and the Anthropic audience `https://api.anthropic.com`. (Project a dedicated service-account token with that audience; don't reuse the IRSA default `sts.amazonaws.com` token.)552553```json554{555  "name": "prod-inference",556  "issuer_id": "fdis_...",557  "match": {558    "subject_prefix": "system:serviceaccount:inference:inference-worker",559    "audience": "https://api.anthropic.com"560  },561  "target": { "type": "service_account", "service_account_id": "svac_..." },562  "workspace_id": "wrkspc_...",563  "oauth_scope": "workspace:developer",564  "token_lifetime_seconds": 600565}566```567568Be 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.569570### Acquire and use the token571572Inside the pod, the projected token is at `/var/run/secrets/anthropic.com/token` (exposed as `ANTHROPIC_IDENTITY_TOKEN_FILE` in the Pod spec). Pass that file to the SDK's federation credentials and the SDK handles the exchange and refresh.573574<CodeGroup>575  ```bash cURL576  JWT=$(cat "$ANTHROPIC_IDENTITY_TOKEN_FILE")577578  RESPONSE=$(curl -sS https://api.anthropic.com/v1/oauth/token \579    -H "content-type: application/json" \580    --data @- <<JSON581  {582    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",583    "assertion": "$JWT",584    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",585    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",586    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",587    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"588  }589  JSON590  )591592  ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r .access_token)593594  curl https://api.anthropic.com/v1/messages \595    -H "authorization: Bearer $ACCESS_TOKEN" \596    -H "anthropic-version: 2023-06-01" \597    -H "content-type: application/json" \598    -d '{599      "model": "claude-opus-5",600      "max_tokens": 1024,601      "messages": [{"role": "user", "content": "Hello from EKS"}]602    }' | jq -r '.content[] | select(.type == "text") | .text'603  ```604605  ```python Python606  import os607608  import anthropic609  from anthropic import IdentityTokenFile, WorkloadIdentityCredentials610611  client = anthropic.Anthropic(612      credentials=WorkloadIdentityCredentials(613          identity_token_provider=IdentityTokenFile(614              os.environ["ANTHROPIC_IDENTITY_TOKEN_FILE"]615          ),616          federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],617          organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],618          service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],619          workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),620      ),621  )622623  message = client.messages.create(624      model="claude-opus-5",625      max_tokens=1024,626      messages=[{"role": "user", "content": "Hello from EKS"}],627  )628  print(next(block.text for block in message.content if block.type == "text"))629  ```630631  ```typescript TypeScript632  import Anthropic from "@anthropic-ai/sdk";633  import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";634  import { identityTokenFromFile } from "@anthropic-ai/sdk/lib/credentials/identity-token";635636  const client = new Anthropic({637    credentials: oidcFederationProvider({638      identityTokenProvider: identityTokenFromFile(process.env.ANTHROPIC_IDENTITY_TOKEN_FILE!),639      federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,640      organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,641      serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,642      workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,643      baseURL: "https://api.anthropic.com",644      fetch645    })646  });647648  const message = await client.messages.create({649    model: "claude-opus-5",650    max_tokens: 1024,651    messages: [{ role: "user", content: "Hello from EKS" }]652  });653  for (const block of message.content) {654    if (block.type === "text") {655      console.log(block.text);656    }657  }658  ```659660  ```go Go661  tokenPath := os.Getenv("ANTHROPIC_IDENTITY_TOKEN_FILE")662663  readToken := option.IdentityTokenFunc(func(ctx context.Context) (string, error) {664  	raw, err := os.ReadFile(tokenPath)665  	if err != nil {666  		return "", fmt.Errorf("read identity token: %w", err)667  	}668  	return string(raw), nil669  })670671  client := anthropic.NewClient(672  	option.WithFederationTokenProvider(readToken, option.FederationOptions{673  		FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),674  		OrganizationID:   os.Getenv("ANTHROPIC_ORGANIZATION_ID"),675  		ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),676  		WorkspaceID:      os.Getenv("ANTHROPIC_WORKSPACE_ID"),677  	}),678  )679680  message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{681  	Model:     anthropic.ModelClaudeOpus5,682  	MaxTokens: 1024,683  	Messages: []anthropic.MessageParam{684  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from EKS")),685  	},686  })687  if err != nil {688  	panic(err)689  }690  for _, block := range message.Content {691  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {692  		fmt.Println(textBlock.Text)693  		break694  	}695  }696  ```697698  ```java Java699  AnthropicClient client = AnthropicOkHttpClient.fromEnv();700701  var message = client.messages().create(MessageCreateParams.builder()702          .model(Model.CLAUDE_OPUS_5)703          .maxTokens(1024)704          .addUserMessage("Hello from EKS")705          .build());706707  IO.println(message.content());708  ```709710  ```csharp C#711  // Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,712  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE713  // from the pod's environment.714  using var client = new AnthropicClient();715716  var message = await client.Messages.Create(new()717  {718      Model = Model.ClaudeOpus5,719      MaxTokens = 1024,720      Messages = [new() { Role = Role.User, Content = "Hello from EKS" }],721  });722  foreach (var block in message.Content)723  {724      if (block.Value is TextBlock textBlock)725      {726          Console.WriteLine(textBlock.Text);727      }728  }729  ```730731  ```bash CLI732  # Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,733  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE734  ant messages create \735    --model claude-opus-5 \736    --max-tokens 1024 \737    --message '{role: user, content: "Hello from EKS"}'738  ```739740  ```php PHP741  use Anthropic\Client;742743  // Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,744  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE745  $client = new Client();746747  $message = $client->messages->create(748      model: 'claude-opus-5',749      maxTokens: 1024,750      messages: [['role' => 'user', 'content' => 'Hello from EKS']],751  );752  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');753  echo $textBlock->text, PHP_EOL;754  ```755756  ```ruby Ruby757  require "anthropic"758759  # Reads ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,760  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and ANTHROPIC_IDENTITY_TOKEN_FILE761  client = Anthropic::Client.new762763  message = client.messages.create(764    model: "claude-opus-5",765    max_tokens: 1024,766    messages: [{role: "user", content: "Hello from EKS"}]767  )768  puts message.content.find { it.type == :text }.text769  ```770</CodeGroup>771772<Tip>773  The Pod spec already sets `ANTHROPIC_IDENTITY_TOKEN_FILE`, `ANTHROPIC_FEDERATION_RULE_ID`, `ANTHROPIC_ORGANIZATION_ID`, `ANTHROPIC_SERVICE_ACCOUNT_ID`, and `ANTHROPIC_WORKSPACE_ID`, so you can construct the client with no arguments and the SDK reads the federation environment variables automatically.774</Tip>775776### Verify the setup777778From inside the pod, exchange the projected token directly and inspect the response:779780```bash cURL781JWT=$(cat "$ANTHROPIC_IDENTITY_TOKEN_FILE")782783curl -sS https://api.anthropic.com/v1/oauth/token \784  -H "content-type: application/json" \785  -d "{786    \"grant_type\": \"urn:ietf:params:oauth:grant-type:jwt-bearer\",787    \"assertion\": \"$JWT\",788    \"federation_rule_id\": \"$ANTHROPIC_FEDERATION_RULE_ID\",789    \"organization_id\": \"$ANTHROPIC_ORGANIZATION_ID\",790    \"service_account_id\": \"$ANTHROPIC_SERVICE_ACCOUNT_ID\",791    \"workspace_id\": \"$ANTHROPIC_WORKSPACE_ID\"792  }" | jq793```794795A 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 EKS-side cause is the projected token's `aud` not matching the rule (project a token with `audience: https://api.anthropic.com`, not the IRSA default `sts.amazonaws.com`).796797## Scope your rule798799<Warning>800  A `subject_prefix` of `arn:aws:iam::123456789012:role/*` matches every IAM role in the account. Any principal that can assume any matching role can obtain a federated Anthropic token.801</Warning>802803Lock the rule's `match` block to the narrowest scope that fits your use case:804805* **Pin the full role ARN:** Use `subject_prefix: "arn:aws:iam::<account>:role/<role-name>"` with no trailing `*` so other roles in the account do not match.806* **Pin the account ID:** Match the `aws_account` field of the token's `https://sts.amazonaws.com/` claim with the `claims` map or a CEL `condition` as a defense-in-depth check against a misconfigured prefix.807* **Pin namespace and service account on EKS:** Use the exact `system:serviceaccount:<namespace>:<name>` value with no `*` after the `system:serviceaccount:` prefix.808* **Use a separate rule per environment:** Create distinct rules for production, staging, and development workloads rather than widening one prefix to cover them all.809810## Next steps811812* Review the [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference) for the full credential precedence, profile configuration, and rule matching reference.813* For self-managed Kubernetes clusters that aren't on EKS, see [Use WIF with Kubernetes](https://platform.claude.com/docs/en/manage-claude/wif-providers/kubernetes).814
Files main
Menu

Theme