---
title: Usare WIF con AWS
url: https://platform.claude.com/docs/it/manage-claude/wif-providers/aws
description: Autentica i workload AWS su Lambda, EC2, ECS o EKS alla Claude API con Workload Identity Federation e token di identità emessi da STS.
---

I workload AWS possono autenticarsi alla Claude API senza chiavi API statiche scambiando un token di identità OIDC firmato da AWS. Il percorso consigliato chiama l'API AWS STS [`GetWebIdentityToken`](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetWebIdentityToken.html), che funziona ovunque il workload disponga di credenziali AWS: Lambda, EC2, ECS ed EKS. I workload EKS possono in alternativa usare il [percorso con token proiettato di Kubernetes](https://platform.claude.com/docs/it/manage-claude/wif-providers/aws#use-eks-projected-service-account-tokens), che richiede meno passaggi di configurazione ma funziona solo all'interno di un pod.

Questa guida mostra entrambi i percorsi. Per i concetti sottostanti (service account, federation issuer e federation rule), consulta [Workload Identity Federation](https://platform.claude.com/docs/it/manage-claude/workload-identity-federation).

## Prerequisiti

* Familiarità con i [concetti di WIF](https://platform.claude.com/docs/it/manage-claude/workload-identity-federation#concepts): service account, federation issuer e federation rule.
* Un workload AWS (pod EKS, task ECS, funzione Lambda o istanza EC2) con un ruolo IAM associato.
* La CLI `aws` o un AWS SDK disponibile nel workload.
* Permesso di creare service account, federation issuer e federation rule nella Claude Console per la tua organizzazione Anthropic.

## Usare i token web identity di STS (consigliato)

L'API AWS STS `GetWebIdentityToken` restituisce un token OIDC firmato da AWS che attesta l'identità IAM del chiamante. Poiché usa le credenziali AWS ambientali del workload, la stessa integrazione copre Lambda, EC2, ECS ed EKS.

### Configurare AWS

<Steps>
  <Step title="Abilita la outbound web identity federation per l'account">
    Si tratta di un flag a livello di account, disattivato per impostazione predefinita. Nella console AWS, apri **IAM**, scegli **Account settings** e abilita **Outbound web identity federation**. Per abilitarlo in modo programmatico:

    ```bash
    python3 -c "import boto3; boto3.client('iam').enable_outbound_web_identity_federation()"
    ```

    Se non è abilitato, le chiamate a `GetWebIdentityToken` falliscono con `OutboundWebIdentityFederationDisabledException`.
  </Step>

  <Step title="Concedi al ruolo IAM del workload il permesso di chiamare l'API">
    Associa questa policy al ruolo IAM con cui viene eseguita la tua funzione Lambda, istanza EC2 o task ECS:

    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": ["sts:GetWebIdentityToken"],
          "Resource": "*"
        }
      ]
    }
    ```
  </Step>

  <Step title="Trova l'URL dell'issuer STS del tuo account">
    Dopo aver abilitato la outbound federation, la pagina **IAM > Account settings** mostra un campo **Get Token Issuer URL** con un valore nella forma `https://<uuid>.tokens.sts.global.api.aws`. Questo URL è univoco per il tuo account AWS; copialo per il passaggio successivo. Per recuperarlo in modo programmatico:

    ```bash
    python3 -c "import boto3; print(boto3.client('iam').get_outbound_web_identity_federation_info())"
    ```
  </Step>
</Steps>

### Configurare Anthropic

Nella Claude Console, vai alla pagina [Workload identity](https://platform.claude.com/settings/workload-identity-federation) (`platform.claude.com/settings/workload-identity-federation`), fai clic su **Connect workload** e seleziona il riquadro **AWS**. La procedura guidata ti accompagna nella registrazione dell'issuer, nella creazione di un service account e nella creazione di una federation rule.

La procedura guidata crea queste risorse per te. Usa i seguenti valori sia che tu li inserisca nella procedura guidata sia che li invii all'[Admin API](https://platform.claude.com/docs/it/manage-claude/wif-admin-api):

**Federation issuer:** Registra l'URL dell'issuer STS per account che hai copiato nel passaggio precedente. Espone un endpoint JWKS pubblico, quindi usa la modalità discovery.

```json
{
  "name": "aws-sts",
  "issuer_url": "https://<uuid>.tokens.sts.global.api.aws",
  "jwks": { "type": "discovery" }
}
```

**Federation rule:** Fai corrispondere l'audience che passi a `GetWebIdentityToken` e l'ARN del ruolo IAM del ruolo chiamante nel claim `sub`. Il valore di `sub` è l'ARN del ruolo IAM del workload che ha chiamato l'API, nella forma `arn:aws:iam::<account>:role/<role-name>`. Il token contiene anche un claim `https://sts.amazonaws.com/` con `aws_account`, `org_id`, `principal_id` ed eventuali `request_tags` che hai passato; puoi effettuare il match su questi con la mappa `claims` della regola o con una `condition` CEL per un controllo più granulare.

```json
{
  "name": "prod-inference",
  "issuer_id": "fdis_...",
  "match": {
    "subject_prefix": "arn:aws:iam::123456789012:role/inference-worker",
    "audience": "https://api.anthropic.com"
  },
  "target": { "type": "service_account", "service_account_id": "svac_..." },
  "workspace_id": "wrkspc_...",
  "oauth_scope": "workspace:developer",
  "token_lifetime_seconds": 600
}
```

Sii specifico quanto il workload consente. Fai corrispondere l'ARN esatto del ruolo e amplia `subject_prefix` (ad esempio, a `arn:aws:iam::123456789012:role/*`) solo se più ruoli IAM devono essere mappati allo stesso service account Anthropic.

### Acquisire e usare il token

Chiama `GetWebIdentityToken` con `https://api.anthropic.com` come audience, quindi passa il risultato alle credenziali di federazione dell'SDK tramite `identity_token_provider` (typescript: `identityTokenProvider`; php: `identityProvider`; csharp: `IdentityTokenProvider`; go: `option.WithFederationTokenProvider`; java: `IdentityTokenConfig`). Tranne che in Java (vedi il commento in quell'esempio), questa opzione accetta un token provider, quindi l'SDK richiama nuovamente STS a ogni aggiornamento.

<Note>
  `GetWebIdentityToken` è disponibile solo sugli endpoint STS regionali. Se ricevi `'STS' object has no attribute 'get_web_identity_token'` o un errore simile, vincola il tuo client STS a una regione (ad esempio, `boto3.client("sts", region_name="us-east-1")`) e assicurati che il tuo AWS SDK sia abbastanza recente da includere l'API.
</Note>

<CodeGroup>
  ```bash cURL
  JWT=$(aws sts get-web-identity-token \
    --region us-east-1 \
    --audience "https://api.anthropic.com" \
    --signing-algorithm RS256 \
    --duration-seconds 900 \
    --query WebIdentityToken --output text)

  RESPONSE=$(curl -sS https://api.anthropic.com/v1/oauth/token \
    -H "content-type: application/json" \
    --data @- <<JSON
  {
    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
    "assertion": "$JWT",
    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",
    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",
    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",
    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"
  }
  JSON
  )

  ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r .access_token)

  curl https://api.anthropic.com/v1/messages \
    -H "authorization: Bearer $ACCESS_TOKEN" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello from AWS"}]
    }' | jq -r '.content[] | select(.type == "text") | .text'
  ```

  ```python Python
  import os

  import anthropic
  import boto3
  from anthropic import WorkloadIdentityCredentials


  def get_sts_web_identity_token() -> str:
      sts = boto3.client("sts", region_name="us-east-1")
      resp = sts.get_web_identity_token(
          Audience=["https://api.anthropic.com"],
          SigningAlgorithm="RS256",
          DurationSeconds=900,
      )
      return resp["WebIdentityToken"]


  client = anthropic.Anthropic(
      credentials=WorkloadIdentityCredentials(
          identity_token_provider=get_sts_web_identity_token,
          federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],
          organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],
          service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],
          workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),
      ),
  )

  message = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello from AWS"}],
  )
  print(next(block.text for block in message.content if block.type == "text"))
  ```

  ```typescript TypeScript
  import Anthropic from "@anthropic-ai/sdk";
  import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";
  import { STSClient, GetWebIdentityTokenCommand } from "@aws-sdk/client-sts";

  const sts = new STSClient({ region: "us-east-1" });

  async function getStsWebIdentityToken(): Promise<string> {
    const out = await sts.send(
      new GetWebIdentityTokenCommand({
        Audience: ["https://api.anthropic.com"],
        SigningAlgorithm: "RS256",
        DurationSeconds: 900
      })
    );
    return out.WebIdentityToken!;
  }

  const client = new Anthropic({
    credentials: oidcFederationProvider({
      identityTokenProvider: getStsWebIdentityToken,
      federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,
      organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,
      serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,
      workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,
      baseURL: "https://api.anthropic.com",
      fetch
    })
  });

  const message = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello from AWS" }]
  });
  for (const block of message.content) {
    if (block.type === "text") {
      console.log(block.text);
    }
  }
  ```

  ```go Go
  ctx := context.TODO()
  cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-east-1"))
  if err != nil {
  	panic(err)
  }
  stsClient := sts.NewFromConfig(cfg)

  getStsToken := option.IdentityTokenFunc(func(ctx context.Context) (string, error) {
  	out, err := stsClient.GetWebIdentityToken(ctx, &sts.GetWebIdentityTokenInput{
  		Audience:         []string{"https://api.anthropic.com"},
  		SigningAlgorithm: "RS256",
  		DurationSeconds:  aws.Int32(900),
  	})
  	if err != nil {
  		return "", err
  	}
  	return *out.WebIdentityToken, nil
  })

  client := anthropic.NewClient(
  	option.WithFederationTokenProvider(getStsToken, option.FederationOptions{
  		FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),
  		OrganizationID:   os.Getenv("ANTHROPIC_ORGANIZATION_ID"),
  		ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),
  		WorkspaceID:      os.Getenv("ANTHROPIC_WORKSPACE_ID"),
  	}),
  )

  message, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from AWS")),
  	},
  })
  if err != nil {
  	panic(err)
  }
  for _, block := range message.Content {
  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  		fmt.Println(textBlock.Text)
  		break
  	}
  }
  ```

  ```java Java
  import com.anthropic.config.AuthenticationConfig;
  import com.anthropic.config.AuthenticationType;
  import com.anthropic.config.IdentityTokenConfig;
  import com.anthropic.config.InMemoryProfileConfigProvider;
  import com.anthropic.config.ProfileConfig;
  // ...
  import software.amazon.awssdk.regions.Region;
  import software.amazon.awssdk.services.sts.StsClient;
  import software.amazon.awssdk.services.sts.model.GetWebIdentityTokenRequest;

  void main() {
      StsClient sts = StsClient.builder().region(Region.US_EAST_1).build();

      // L'SDK Java accetta il token stesso o un percorso di file, non una funzione; con
      // source("value"), path(...) contiene il token. L'SDK invia lo stesso token
      // a ogni aggiornamento del token di accesso Anthropic, il che fallisce una volta
      // scaduto o, se ha un claim jti, già usato. Per un processo di lunga durata,
      // passa source("file") e scrivi un nuovo token nel file prima di
      // ogni aggiornamento.
      String stsToken = sts.getWebIdentityToken(
                      GetWebIdentityTokenRequest.builder()
                              .audience("https://api.anthropic.com")
                              .signingAlgorithm("RS256")
                              .durationSeconds(900)
                              .build())
              .webIdentityToken();

      AnthropicClient client = AnthropicOkHttpClient.builder()
              .configurationProvider(InMemoryProfileConfigProvider.of(ProfileConfig.builder()
                      .organizationId(System.getenv("ANTHROPIC_ORGANIZATION_ID"))
                      .workspaceId(System.getenv("ANTHROPIC_WORKSPACE_ID"))
                      .authentication(AuthenticationConfig.builder()
                              .type(AuthenticationType.OIDC_FEDERATION)
                              .federationRuleId(System.getenv("ANTHROPIC_FEDERATION_RULE_ID"))
                              .serviceAccountId(System.getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"))
                              .identityToken(IdentityTokenConfig.builder()
                                      .source("value")
                                      .path(stsToken)
                                      .build())
                              .build())
                      .build()))
              .build();

      var message = client.messages().create(MessageCreateParams.builder()
              .model(Model.CLAUDE_OPUS_5_5)
              .maxTokens(1024)
              .addUserMessage("Hello from AWS")
              .build());

      IO.println(message.content());
  }
  ```

  ```csharp C#
  using Amazon.SecurityToken;
  using Amazon.SecurityToken.Model;
  // ...
  using Anthropic.Credentials;
  // ...

  var credentials = new WorkloadIdentityCredentials(new WorkloadIdentityOptions
  {
      FederationRuleId = Environment.GetEnvironmentVariable("ANTHROPIC_FEDERATION_RULE_ID")!,
      OrganizationId = Environment.GetEnvironmentVariable("ANTHROPIC_ORGANIZATION_ID"),
      ServiceAccountId = Environment.GetEnvironmentVariable("ANTHROPIC_SERVICE_ACCOUNT_ID"),
      WorkspaceId = Environment.GetEnvironmentVariable("ANTHROPIC_WORKSPACE_ID"),
      IdentityTokenProvider = new StsTokenProvider(),
  });
  using var client = new AnthropicClient(new ClientOptions { Credentials = credentials });

  var message = await client.Messages.Create(new()
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new() { Role = Role.User, Content = "Hello from AWS" }],
  });
  foreach (var block in message.Content)
  {
      if (block.Value is TextBlock textBlock)
      {
          Console.WriteLine(textBlock.Text);
      }
  }

  class StsTokenProvider : IIdentityTokenProvider
  {
      private readonly AmazonSecurityTokenServiceClient _sts = new(Amazon.RegionEndpoint.USEast1);

      public async Task<string> GetIdentityTokenAsync(CancellationToken ct = default)
      {
          var resp = await _sts.GetWebIdentityTokenAsync(new GetWebIdentityTokenRequest
          {
              Audience = ["https://api.anthropic.com"],
              SigningAlgorithm = "RS256",
              DurationSeconds = 900,
          }, ct);
          return resp.WebIdentityToken;
      }
  }
  ```

  ```bash CLI
  TOKEN_FILE=$(mktemp)
  aws sts get-web-identity-token \
    --region us-east-1 \
    --audience "https://api.anthropic.com" \
    --signing-algorithm RS256 \
    --duration-seconds 900 \
    --query WebIdentityToken --output text > "$TOKEN_FILE"

  export ANTHROPIC_IDENTITY_TOKEN_FILE="$TOKEN_FILE"
  # ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,
  # ANTHROPIC_SERVICE_ACCOUNT_ID e ANTHROPIC_WORKSPACE_ID vengono letti dall'ambiente
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello from AWS"}'
  ```

  ```php PHP
  use Anthropic\Client;
  use Anthropic\Lib\Credentials\CredentialResult;
  use Anthropic\Lib\Credentials\IdentityTokenProvider;
  use Anthropic\Lib\Credentials\TokenCache;
  use Anthropic\Lib\Credentials\WorkloadIdentityCredentials;
  use Aws\Sts\StsClient;

  $sts = new StsClient(['region' => 'us-east-1', 'version' => 'latest']);

  class StsIdentityToken implements IdentityTokenProvider
  {
      public function __construct(private StsClient $sts) {}

      public function getIdentityToken(): string
      {
          return $this->sts->getWebIdentityToken([
              'Audience' => ['https://api.anthropic.com'],
              'SigningAlgorithm' => 'RS256',
              'DurationSeconds' => 900,
          ])['WebIdentityToken'];
      }
  }

  $client = new Client(credentials: new CredentialResult(
      provider: new TokenCache(new WorkloadIdentityCredentials(
          identityProvider: new StsIdentityToken($sts),
          federationRuleId: getenv('ANTHROPIC_FEDERATION_RULE_ID'),
          organizationId: getenv('ANTHROPIC_ORGANIZATION_ID'),
          serviceAccountId: getenv('ANTHROPIC_SERVICE_ACCOUNT_ID'),
          workspaceId: getenv('ANTHROPIC_WORKSPACE_ID') ?: null,
      )),
  ));

  $message = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello from AWS']],
  );
  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');
  echo $textBlock->text, PHP_EOL;
  ```

  ```ruby Ruby
  require "anthropic"
  require "aws-sdk-sts"

  sts = Aws::STS::Client.new(region: "us-east-1")
  client = Anthropic::Client.new(
    credentials: Anthropic::WorkloadIdentityCredentials.new(
      identity_token_provider: -> {
        sts.get_web_identity_token(
          audience: ["https://api.anthropic.com"],
          signing_algorithm: "RS256",
          duration_seconds: 900,
        ).web_identity_token
      },
      federation_rule_id: ENV.fetch("ANTHROPIC_FEDERATION_RULE_ID"),
      organization_id: ENV.fetch("ANTHROPIC_ORGANIZATION_ID"),
      service_account_id: ENV.fetch("ANTHROPIC_SERVICE_ACCOUNT_ID"),
      workspace_id: ENV["ANTHROPIC_WORKSPACE_ID"],
    ),
  )

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello from AWS"}]
  )
  puts message.content.find { it.type == :text }.text
  ```
</CodeGroup>

### Verificare la configurazione

Dall'interno del workload, scambia direttamente un token emesso da STS e ispeziona la risposta:

```bash cURL
JWT=$(aws sts get-web-identity-token \
  --region us-east-1 \
  --audience "https://api.anthropic.com" \
  --signing-algorithm RS256 \
  --duration-seconds 900 \
  --query WebIdentityToken --output text)

curl -sS https://api.anthropic.com/v1/oauth/token \
  -H "content-type: application/json" \
  -d "{
    \"grant_type\": \"urn:ietf:params:oauth:grant-type:jwt-bearer\",
    \"assertion\": \"$JWT\",
    \"federation_rule_id\": \"fdrl_...\",
    \"organization_id\": \"00000000-0000-0000-0000-000000000000\",
    \"service_account_id\": \"svac_...\",
    \"workspace_id\": \"wrkspc_...\"
  }" | jq
```

Uno scambio riuscito restituisce un `access_token` che inizia con `sk-ant-oat01-` e un valore `expires_in` in secondi. Se lo scambio fallisce con la risposta opaca `401` `authentication_error` (messaggio `Authentication failed`), controlla la [pagina della cronologia di autenticazione](https://platform.claude.com/settings/workload-identity-federation?tab=history) nella Claude Console per il motivo del rifiuto e consulta [Risolvere i problemi di uno scambio fallito](https://platform.claude.com/docs/it/manage-claude/wif-reference#troubleshoot-a-failed-exchange); la causa più comune lato AWS è una mancata corrispondenza di `iss` (l'URL dell'issuer STS per account deve corrispondere esattamente all'`issuer_url` registrato).

## Usare i token di service account proiettati di EKS

Se il tuo workload viene eseguito in un pod EKS, puoi saltare la chiamata STS e leggere un token di service account proiettato da Kubernetes direttamente dal disco. Kubernetes proietta nativamente nel pod un token compatibile con OIDC e l'SDK può leggerlo da un percorso di file, quindi non è richiesto alcun callable token provider. Questo percorso ha due passaggi di configurazione AWS in meno rispetto al percorso STS ma funziona solo all'interno di un pod; il meccanismo sottostante è lo stesso dell'[integrazione Kubernetes generica](https://platform.claude.com/docs/it/manage-claude/wif-providers/kubernetes).

Questo percorso richiede inoltre un cluster EKS con un [provider OIDC IAM abilitato](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html) e accesso `kubectl` al cluster.

### Configurare il cluster EKS

<Steps>
  <Step title="Trova l'URL dell'issuer OIDC del tuo cluster">
    Ogni cluster EKS ha un issuer OIDC univoco. Recuperalo con la AWS CLI:

    ```bash CLI
    aws eks describe-cluster \
      --name <cluster-name> \
      --query "cluster.identity.oidc.issuer" \
      --output text
    ```

    L'output ha un aspetto simile a `https://oidc.eks.us-west-2.amazonaws.com/id/6FA42E7BFDE8549CB...`. Registrerai questo URL come federation issuer nella sezione successiva.
  </Step>

  <Step title="Crea il service account e proietta un token con audience Anthropic">
    Il webhook di pod identity di EKS rileva l'annotazione `eks.amazonaws.com/role-arn` e proietta automaticamente un token con `aud: sts.amazonaws.com`, esponendone il percorso come `AWS_WEB_IDENTITY_TOKEN_FILE`. Quel token serve per l'assunzione di ruoli AWS. Per lo scambio Anthropic, proietta un secondo token con `audience: https://api.anthropic.com` e montalo in un percorso dedicato.

    ```yaml
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: inference-worker
      namespace: inference
      annotations:
        eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/inference-worker
    ```

    ```yaml
    apiVersion: v1
    kind: Pod
    metadata:
      name: inference-worker
      namespace: inference
    spec:
      serviceAccountName: inference-worker
      volumes:
        - name: anthropic-token
          projected:
            sources:
              - serviceAccountToken:
                  audience: https://api.anthropic.com
                  expirationSeconds: 3600
                  path: token
      containers:
        - name: app
          image: your-registry/inference-worker:latest
          env:
            - name: ANTHROPIC_IDENTITY_TOKEN_FILE
              value: /var/run/secrets/anthropic.com/token
            - name: ANTHROPIC_FEDERATION_RULE_ID
              value: fdrl_...
            - name: ANTHROPIC_ORGANIZATION_ID
              value: 00000000-0000-0000-0000-000000000000
            - name: ANTHROPIC_SERVICE_ACCOUNT_ID
              value: svac_...
            - name: ANTHROPIC_WORKSPACE_ID  # required when the rule covers multiple workspaces
              value: wrkspc_...
          volumeMounts:
            - name: anthropic-token
              mountPath: /var/run/secrets/anthropic.com
              readOnly: true
    ```
  </Step>

  <Step title="Prendi nota della struttura dei claim del token">
    Il token proiettato è un JSON Web Token (JWT) firmato dall'issuer OIDC del tuo cluster. Il suo claim `sub` segue la convenzione Kubernetes `system:serviceaccount:<namespace>:<service-account-name>`:

    ```json
    {
      "iss": "https://oidc.eks.us-west-2.amazonaws.com/id/6FA42E7BFDE8549CB...",
      "sub": "system:serviceaccount:inference:inference-worker",
      "aud": ["https://api.anthropic.com"],
      "kubernetes.io": {
        "namespace": "inference",
        "serviceaccount": { "name": "inference-worker", "uid": "..." }
      },
      "exp": 1775527120,
      "iat": 1775523520
    }
    ```

    La proiezione `serviceAccountToken` imposta `aud` a `https://api.anthropic.com`. Il token separato iniettato da IRSA in `AWS_WEB_IDENTITY_TOKEN_FILE` contiene `aud: sts.amazonaws.com` e serve per le chiamate alle API AWS, non per questo scambio.
  </Step>
</Steps>

### Configurare Anthropic

Nella Claude Console, vai alla pagina [Workload identity](https://platform.claude.com/settings/workload-identity-federation) (`platform.claude.com/settings/workload-identity-federation`), fai clic su **Connect workload** e seleziona il riquadro **AWS**. La procedura guidata ti accompagna nella registrazione dell'issuer, nella creazione di un service account e nella creazione di una federation rule.

La procedura guidata crea queste risorse per te. Usa i seguenti valori sia che tu li inserisca nella procedura guidata sia che li invii all'[Admin API](https://platform.claude.com/docs/it/manage-claude/wif-admin-api):

**Federation issuer:** Gli issuer EKS espongono un endpoint JWKS pubblico, quindi usa la modalità discovery. L'URL dell'issuer deve corrispondere esattamente al claim `iss` del token. Registra un issuer per cluster.

```json
{
  "name": "prod-eks-uswest2",
  "issuer_url": "https://oidc.eks.us-west-2.amazonaws.com/id/6FA42E7BFDE8549CB...",
  "jwks": { "type": "discovery" }
}
```

**Federation rule:** Fai corrispondere il claim `sub` di Kubernetes e l'audience Anthropic `https://api.anthropic.com`. (Proietta un token di service account dedicato con quell'audience; non riutilizzare il token predefinito IRSA `sts.amazonaws.com`.)

```json
{
  "name": "prod-inference",
  "issuer_id": "fdis_...",
  "match": {
    "subject_prefix": "system:serviceaccount:inference:inference-worker",
    "audience": "https://api.anthropic.com"
  },
  "target": { "type": "service_account", "service_account_id": "svac_..." },
  "workspace_id": "wrkspc_...",
  "oauth_scope": "workspace:developer",
  "token_lifetime_seconds": 600
}
```

Sii specifico quanto il workload consente. Allenta `subject_prefix` a `system:serviceaccount:inference:*` (il `*` finale lo rende un match per prefisso) solo se ogni service account nel namespace deve essere mappato allo stesso service account Anthropic.

### Acquisire e usare il token

All'interno del pod, il token proiettato si trova in `/var/run/secrets/anthropic.com/token` (esposto come `ANTHROPIC_IDENTITY_TOKEN_FILE` nella specifica del Pod). Passa quel file alle credenziali di federazione dell'SDK e l'SDK gestisce lo scambio e il refresh.

<CodeGroup>
  ```bash cURL
  JWT=$(cat "$ANTHROPIC_IDENTITY_TOKEN_FILE")

  RESPONSE=$(curl -sS https://api.anthropic.com/v1/oauth/token \
    -H "content-type: application/json" \
    --data @- <<JSON
  {
    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
    "assertion": "$JWT",
    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",
    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",
    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",
    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"
  }
  JSON
  )

  ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r .access_token)

  curl https://api.anthropic.com/v1/messages \
    -H "authorization: Bearer $ACCESS_TOKEN" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello from EKS"}]
    }' | jq -r '.content[] | select(.type == "text") | .text'
  ```

  ```python Python
  import os

  import anthropic
  from anthropic import IdentityTokenFile, WorkloadIdentityCredentials

  client = anthropic.Anthropic(
      credentials=WorkloadIdentityCredentials(
          identity_token_provider=IdentityTokenFile(
              os.environ["ANTHROPIC_IDENTITY_TOKEN_FILE"]
          ),
          federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],
          organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],
          service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],
          workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),
      ),
  )

  message = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello from EKS"}],
  )
  print(next(block.text for block in message.content if block.type == "text"))
  ```

  ```typescript TypeScript
  import Anthropic from "@anthropic-ai/sdk";
  import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";
  import { identityTokenFromFile } from "@anthropic-ai/sdk/lib/credentials/identity-token";

  const client = new Anthropic({
    credentials: oidcFederationProvider({
      identityTokenProvider: identityTokenFromFile(process.env.ANTHROPIC_IDENTITY_TOKEN_FILE!),
      federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,
      organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,
      serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,
      workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,
      baseURL: "https://api.anthropic.com",
      fetch
    })
  });

  const message = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello from EKS" }]
  });
  for (const block of message.content) {
    if (block.type === "text") {
      console.log(block.text);
    }
  }
  ```

  ```go Go
  tokenPath := os.Getenv("ANTHROPIC_IDENTITY_TOKEN_FILE")

  readToken := option.IdentityTokenFunc(func(ctx context.Context) (string, error) {
  	raw, err := os.ReadFile(tokenPath)
  	if err != nil {
  		return "", fmt.Errorf("read identity token: %w", err)
  	}
  	return string(raw), nil
  })

  client := anthropic.NewClient(
  	option.WithFederationTokenProvider(readToken, option.FederationOptions{
  		FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),
  		OrganizationID:   os.Getenv("ANTHROPIC_ORGANIZATION_ID"),
  		ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),
  		WorkspaceID:      os.Getenv("ANTHROPIC_WORKSPACE_ID"),
  	}),
  )

  message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from EKS")),
  	},
  })
  if err != nil {
  	panic(err)
  }
  for _, block := range message.Content {
  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  		fmt.Println(textBlock.Text)
  		break
  	}
  }
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  var message = client.messages().create(MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024)
          .addUserMessage("Hello from EKS")
          .build());

  IO.println(message.content());
  ```

  ```csharp C#
  // Legge ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,
  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID e ANTHROPIC_IDENTITY_TOKEN_FILE
  // dall'ambiente del pod.
  using var client = new AnthropicClient();

  var message = await client.Messages.Create(new()
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new() { Role = Role.User, Content = "Hello from EKS" }],
  });
  foreach (var block in message.Content)
  {
      if (block.Value is TextBlock textBlock)
      {
          Console.WriteLine(textBlock.Text);
      }
  }
  ```

  ```bash CLI
  # Legge ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,
  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID e ANTHROPIC_IDENTITY_TOKEN_FILE
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello from EKS"}'
  ```

  ```php PHP
  use Anthropic\Client;

  // Legge ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,
  // ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID e ANTHROPIC_IDENTITY_TOKEN_FILE
  $client = new Client();

  $message = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello from EKS']],
  );
  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');
  echo $textBlock->text, PHP_EOL;
  ```

  ```ruby Ruby
  require "anthropic"

  # Legge ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,
  # ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID e ANTHROPIC_IDENTITY_TOKEN_FILE
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{role: "user", content: "Hello from EKS"}]
  )
  puts message.content.find { it.type == :text }.text
  ```
</CodeGroup>

<Tip>
  La specifica del Pod imposta già `ANTHROPIC_IDENTITY_TOKEN_FILE`, `ANTHROPIC_FEDERATION_RULE_ID`, `ANTHROPIC_ORGANIZATION_ID`, `ANTHROPIC_SERVICE_ACCOUNT_ID` e `ANTHROPIC_WORKSPACE_ID`, quindi puoi costruire il client senza argomenti e l'SDK legge automaticamente le variabili d'ambiente di federazione.
</Tip>

### Verificare la configurazione

Dall'interno del pod, scambia direttamente il token proiettato e ispeziona la risposta:

```bash cURL
JWT=$(cat "$ANTHROPIC_IDENTITY_TOKEN_FILE")

curl -sS https://api.anthropic.com/v1/oauth/token \
  -H "content-type: application/json" \
  -d "{
    \"grant_type\": \"urn:ietf:params:oauth:grant-type:jwt-bearer\",
    \"assertion\": \"$JWT\",
    \"federation_rule_id\": \"$ANTHROPIC_FEDERATION_RULE_ID\",
    \"organization_id\": \"$ANTHROPIC_ORGANIZATION_ID\",
    \"service_account_id\": \"$ANTHROPIC_SERVICE_ACCOUNT_ID\",
    \"workspace_id\": \"$ANTHROPIC_WORKSPACE_ID\"
  }" | jq
```

Uno scambio riuscito restituisce un `access_token` che inizia con `sk-ant-oat01-` e un valore `expires_in` in secondi. Se lo scambio fallisce con la risposta opaca `401` `authentication_error` (messaggio `Authentication failed`), controlla la [pagina della cronologia di autenticazione](https://platform.claude.com/settings/workload-identity-federation?tab=history) nella Claude Console per il motivo del rifiuto e consulta [Risolvere i problemi di uno scambio fallito](https://platform.claude.com/docs/it/manage-claude/wif-reference#troubleshoot-a-failed-exchange); la causa più comune lato EKS è che l'`aud` del token proiettato non corrisponde alla regola (proietta un token con `audience: https://api.anthropic.com`, non il valore predefinito IRSA `sts.amazonaws.com`).

## Definire l'ambito della regola

<Warning>
  Un `subject_prefix` pari a `arn:aws:iam::123456789012:role/*` corrisponde a ogni ruolo IAM nell'account. Qualsiasi principal che possa assumere un qualsiasi ruolo corrispondente può ottenere un token Anthropic federato.
</Warning>

Vincola il blocco `match` della regola all'ambito più ristretto adatto al tuo caso d'uso:

* **Fissa l'ARN completo del ruolo:** Usa `subject_prefix: "arn:aws:iam::<account>:role/<role-name>"` senza `*` finale in modo che gli altri ruoli nell'account non corrispondano.
* **Fissa l'ID dell'account:** Fai corrispondere il campo `aws_account` del claim `https://sts.amazonaws.com/` del token con la mappa `claims` o una `condition` CEL come controllo di difesa in profondità contro un prefisso configurato in modo errato.
* **Fissa namespace e service account su EKS:** Usa il valore esatto `system:serviceaccount:<namespace>:<name>` senza `*` dopo il prefisso `system:serviceaccount:`.
* **Usa una regola separata per ambiente:** Crea regole distinte per i workload di produzione, staging e sviluppo invece di ampliare un unico prefisso per coprirli tutti.

## Passaggi successivi

* Consulta il [riferimento WIF](https://platform.claude.com/docs/it/manage-claude/wif-reference) per il riferimento completo sulla precedenza delle credenziali, la configurazione dei profili e il matching delle regole.
* Per i cluster Kubernetes autogestiti che non sono su EKS, consulta [Usare WIF con Kubernetes](https://platform.claude.com/docs/it/manage-claude/wif-providers/kubernetes).
