SPB Git

Repository Public

azure.md 63.5 KB 1,219 lines markdown

1---2title: Use WIF with Microsoft Entra ID3url: https://platform.claude.com/docs/en/manage-claude/wif-providers/azure4description: Federate Azure managed identities and Entra Workload Identity with the Claude API so your Azure workloads can call Claude without static API keys.5---67Azure workloads authenticate to the Claude API by presenting a JSON Web Token (JWT) issued by Microsoft Entra ID, then exchanging it for a short-lived Anthropic access token. The setup follows the same shape on every Azure platform:891. **Register the token audience:** Create one app registration in your Microsoft Entra tenant to represent the Claude API audience. Every workload in the tenant requests Entra tokens for it.102. **Set up the identity for your platform:** A managed identity on VMs, VM Scale Sets, App Service, Functions, and Container Apps, or Entra Workload Identity on AKS.113. **Configure Anthropic:** Register your tenant's Entra issuer, create a service account, and write a federation rule that matches the token's claims.124. **Exchange at runtime:** Your workload exchanges its Entra-issued token at `POST /v1/oauth/token` for an `sk-ant-oat01-...` Anthropic access token and calls Claude with it.1314On both paths the token you present to Anthropic carries your tenant-specific Entra issuer and the managed identity's object ID in the `sub` and `oid` claims; only how the workload obtains that token differs. Pick the section for where your workload runs: [Use a managed identity](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#use-a-managed-identity) for VMs, VM Scale Sets, App Service, Functions, or Container Apps; [Use Entra Workload Identity on AKS](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#use-entra-workload-identity-on-aks) for AKS.1516## Prerequisites1718* Familiarity with [WIF concepts](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#concepts): service accounts, federation issuers, and federation rules.19* An Azure subscription with permission to assign managed identities (or configure Entra Workload Identity on AKS).20* Permission to create one app registration and service principal in your Microsoft Entra tenant (the shared Claude API audience). Entra only issues tokens for an audience that exists in the tenant, so the [Register the token audience](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#register-the-token-audience) step is required before any token request succeeds.21* Your Microsoft Entra tenant ID. Find it in the Azure portal under **Microsoft Entra ID → Overview → Tenant ID**.22* Permission to create service accounts, federation issuers, and federation rules in the Claude Console for your Anthropic organization.2324## Register the token audience2526Microsoft Entra ID only issues a token when the requested audience exists in your tenant as an app registration with a service principal. Create one app registration to represent the Claude API audience; every workload in the tenant can request tokens for it. Without this registration, token requests fail with a "resource not found in tenant" error (`AADSTS50001` from the managed identity endpoints, `AADSTS500011` from the Entra token endpoint).2728```bash29# Create the app registration that represents the Claude API audience.30APP_ID=$(az ad app create --display-name claude-api-federation --query appId -o tsv)3132# Request v2.0 access tokens and set the api://<APP_ID> identifier URI.33az ad app update --id "$APP_ID" \34  --identifier-uris "api://$APP_ID" \35  --set api.requestedAccessTokenVersion=23637# Create the service principal so the audience resolves in your tenant.38az ad sp create --id "$APP_ID"39```4041<Note>42  Use the `api://<APP_ID>` identifier URI format. Entra restricts `https://` identifier URIs to verified domains of your own tenant, so a URI such as `https://api.anthropic.com` cannot be registered in most tenants; `api://<APP_ID>` is accepted everywhere. With `requestedAccessTokenVersion: 2`, tokens for this audience are v2.0, which is what this guide assumes. If you reuse an existing registration that emits v1.0 tokens, see [If your tokens are v1.0](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#if-your-tokens-are-v1-0).43</Note>4445## Use a managed identity4647Use this path when your workload runs on a VM, a VM Scale Set, App Service, Functions, or Container Apps. The workload requests an Entra-issued JWT for its assigned managed identity from the platform's local token endpoint, then exchanges that JWT with Anthropic.4849### Configure the managed identity5051<Steps>52  <Step title="Attach a managed identity">53    Enable a system-assigned or user-assigned managed identity on your Azure resource. In the Azure portal, open the resource, go to **Identity**, and turn on **System assigned** (or attach a user-assigned identity).5455    After the identity is created, note its **Object (principal) ID**. This GUID appears as both the `sub` and `oid` claims in the issued token, and your Anthropic federation rule will match on it. You can find it on the resource's **Identity** page; for a user-assigned identity, it is the **Object (principal) ID** on the managed identity resource's **Overview** page. (A managed identity has only a service principal in Microsoft Entra ID, not an app registration.)56  </Step>5758  <Step title="Find the platform's token endpoint">59    The platform exposes a local token endpoint once the identity is attached:6061    * **VMs and VM Scale Sets:** IMDS at `http://169.254.169.254/metadata/identity/oauth2/token` with the header `Metadata: true` and `api-version=2018-02-01`.62    * **App Service, Functions, and Container Apps:** The URL in the `IDENTITY_ENDPOINT` environment variable with the header `X-IDENTITY-HEADER` set to the value of `IDENTITY_HEADER`, and `api-version=2019-08-01`. IMDS is not reachable on these platforms.6364    If the resource has more than one user-assigned managed identity, add `client_id=<IDENTITY_CLIENT_ID>` to the token request to select one. Azure recommends always specifying it. Without it, the outcome depends on whether the resource also has a system-assigned identity enabled: if it does, the request silently falls back to that identity and then fails your federation rule's `oid` match; if it does not, the request fails outright as soon as a second user-assigned identity is attached.65  </Step>6667  <Step title="Decode a sample token">68    Request a token from the endpoint and decode its payload to confirm the claims your federation rule needs to match. (For the decode command, see [Troubleshoot a failed exchange](https://platform.claude.com/docs/en/manage-claude/wif-reference#troubleshoot-a-failed-exchange).) A v2.0 token for a managed identity carries these claims:6970    ```json71    {72      "iss": "https://login.microsoftonline.com/<TENANT_ID>/v2.0",73      "sub": "9f8e7d6c-1a2b-3c4d-5e6f-...",74      "aud": "<APP_ID>",75      "oid": "9f8e7d6c-1a2b-3c4d-5e6f-...",76      "tid": "<TENANT_ID>",77      "azp": "<IDENTITY_CLIENT_ID>",78      "ver": "2.0",79      "exp": 177552712080    }81    ```8283    | Claim | Value                                                                                                                                                                                                 | Match this when                                                                                                                                                                                                    |84    | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |85    | `oid` | The managed identity's object ID, identical to `sub`                                                                                                                                                  | You want to authorize one specific managed identity. This is the default; the rule in [Configure Anthropic](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#configure-anthropic) matches it. |86    | `azp` | The calling identity's client ID                                                                                                                                                                      | You want to authorize every workload that shares one app registration. For a managed identity, `azp` is unique to that identity, so it is equivalent to `oid`.                                                     |87    | `aud` | The audience app registration's client ID (the `<APP_ID>` GUID from [Register the token audience](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#register-the-token-audience)) | Always. The rule's `audience` field must equal the token's `aud` value exactly.                                                                                                                                    |88    | `tid` | Your tenant ID                                                                                                                                                                                        | You want defense in depth. The issuer URL already pins the tenant.                                                                                                                                                 |8990    If the decoded token's `ver` claim is `1.0`, the claim names and values differ. See [If your tokens are v1.0](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#if-your-tokens-are-v1-0) before continuing.91  </Step>92</Steps>9394### Configure Anthropic9596In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select the **Microsoft Entra** tile. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.9798The 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):99100**Federation issuer:** Choose **v2.0 (login.microsoftonline.com)** in the wizard's **Token issuer** selector. (The selector defaults to v1; that default exists for tenants reusing older registrations that still emit v1.0 tokens.) Entra publishes an OIDC discovery document at the per-tenant issuer URL, so use discovery mode. Each Microsoft Entra tenant you federate needs its own issuer record.101102```json103{104  "name": "azure-prod-tenant",105  "issuer_url": "https://login.microsoftonline.com/<TENANT_ID>/v2.0",106  "jwks": { "type": "discovery" },107  "max_jwt_lifetime_seconds": 86400108}109```110111<Warning>112  Managed identity workloads need `max_jwt_lifetime_seconds: 86400`. Azure issues managed identity tokens with up to 24 hours between `iat` and `exp` because it caches each resource's token for that window and offers no way to force an early refresh, and the issuer's 1-hour default rejects those tokens, so the exchange fails with the opaque `401` `authentication_error` response (message `Authentication failed`). The Connect workload wizard's Microsoft Entra tile creates the issuer with `max_jwt_lifetime_seconds` set to `7500` and provides no field to change it during creation, so finish the wizard, then open **Settings → Workload identity → Issuers**, edit the issuer, and raise the value to `86400`. You can also update the issuer through the Admin API.113</Warning>114115A longer accepted lifetime means a leaked Entra token stays exchangeable for longer. If a token leaks, the lever is disabling the federation rule; a tight `oid` match limits which identities can exchange a token in the first place, as described in [Scope your rule](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#scope-your-rule).116117**Federation rule:** Match on the managed identity's object ID and your tenant ID. For the v2.0 tokens this guide configures, the `audience` value is the audience app registration's client ID (the `<APP_ID>` GUID from [Register the token audience](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#register-the-token-audience)). Use the exact `aud` value from your decoded token.118119```json120{121  "name": "azure-inference-worker",122  "issuer_id": "fdis_...",123  "match": {124    "audience": "<APP_ID>",125    "claims": {126      "oid": "9f8e7d6c-1a2b-3c4d-5e6f-...",127      "tid": "<TENANT_ID>"128    }129  },130  "target": {131    "type": "service_account",132    "service_account_id": "svac_..."133  },134  "workspace_id": "wrkspc_...",135  "oauth_scope": "workspace:developer",136  "token_lifetime_seconds": 600137}138```139140`token_lifetime_seconds` is the lifetime of the Anthropic access token the exchange returns, not of the Entra token; the SDK refreshes it for you.141142### Acquire and use the token143144At runtime your workload fetches its Entra token, exchanges it at `POST /v1/oauth/token`, and uses the returned bearer token to call Claude. Each Anthropic SDK handles the exchange and refresh loop when you supply a token-provider callable, as shown in the following examples. The cURL tab shows the raw flow.145146The samples fetch the managed identity token from the platform's token endpoint: IMDS on VMs and VM Scale Sets, or the `IDENTITY_ENDPOINT` service on App Service, Functions, and Container Apps. Replace `<APP_ID>` in the `api://<APP_ID>` resource value with the audience app registration's client ID from [Register the token audience](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#register-the-token-audience).147148<Tip>149  If your workload already uses the Azure Identity client library, pass its token acquisition (`DefaultAzureCredential` with the scope `api://<APP_ID>/.default`) as the identity token provider instead of calling the token endpoints directly. The library selects the correct endpoint on every Azure platform, including AKS with Entra Workload Identity.150</Tip>151152<CodeGroup>153  ```bash cURL154  # 1. Fetch the Entra-issued token (managed identity).155  #    On a VM or VM Scale Set, use IMDS. With multiple user-assigned156  #    identities, append &client_id=<IDENTITY_CLIENT_ID>.157  ENTRA_TOKEN=$(curl -sS -H "Metadata: true" \158    "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=api://<APP_ID>" \159    | jq -r .access_token)160161  #    On App Service, Functions, or Container Apps, use the local token162  #    service instead (IMDS is not reachable there):163  # ENTRA_TOKEN=$(curl -sS -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" \164  #   "$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=api://<APP_ID>" \165  #   | jq -r .access_token)166167  #    For AKS with Entra Workload Identity, use the two-hop exchange in the168  #    "Use Entra Workload Identity on AKS" section instead.169170  # 2. Exchange it for an Anthropic access token.171  RESPONSE=$(curl -sS https://api.anthropic.com/v1/oauth/token \172    -H "content-type: application/json" \173    -d @- <<JSON174  {175    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",176    "assertion": "$ENTRA_TOKEN",177    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",178    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",179    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",180    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"181  }182  JSON183  )184185  ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r .access_token)186187  # 3. Call the Claude API with the bearer token.188  curl https://api.anthropic.com/v1/messages \189    -H "authorization: Bearer $ACCESS_TOKEN" \190    -H "anthropic-version: 2023-06-01" \191    -H "content-type: application/json" \192    -d '{193      "model": "claude-opus-5",194      "max_tokens": 1024,195      "messages": [{"role": "user", "content": "Hello from Azure"}]196    }' | jq -r '.content[] | select(.type == "text") | .text'197  ```198199  ```python Python200  import os201202  import anthropic203  import requests204  from anthropic import WorkloadIdentityCredentials205206  # The audience app registration's identifier URI (see Register the token audience).207  AUDIENCE = "api://<APP_ID>"208209210  def fetch_entra_token() -> str:211      """Fetch a managed identity token from the platform's token endpoint."""212      # With multiple user-assigned identities, add client_id=<IDENTITY_CLIENT_ID>213      # to the request params to select one.214      if endpoint := os.environ.get("IDENTITY_ENDPOINT"):215          # App Service, Functions, Container Apps216          response = requests.get(217              endpoint,218              headers={"X-IDENTITY-HEADER": os.environ["IDENTITY_HEADER"]},219              params={"api-version": "2019-08-01", "resource": AUDIENCE},220              timeout=5,221          )222      else:223          # VM or VM Scale Set: Azure Instance Metadata Service (IMDS)224          response = requests.get(225              "http://169.254.169.254/metadata/identity/oauth2/token",226              headers={"Metadata": "true"},227              params={"api-version": "2018-02-01", "resource": AUDIENCE},228              timeout=5,229          )230      response.raise_for_status()231      return response.json()["access_token"]232233234  client = anthropic.Anthropic(235      credentials=WorkloadIdentityCredentials(236          identity_token_provider=fetch_entra_token,237          federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],238          organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],239          service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],240          workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),241      ),242  )243244  message = client.messages.create(245      model="claude-opus-5",246      max_tokens=1024,247      messages=[{"role": "user", "content": "Hello from Azure"}],248  )249  print(next(block.text for block in message.content if block.type == "text"))250  ```251252  ```typescript TypeScript253  import Anthropic from "@anthropic-ai/sdk";254  import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";255256  // The audience app registration's identifier URI (see Register the token audience).257  const AUDIENCE = "api://<APP_ID>";258259  async function fetchEntraToken(): Promise<string> {260    // App Service, Functions, and Container Apps inject IDENTITY_ENDPOINT;261    // VMs and VM Scale Sets use IMDS.262    // With multiple user-assigned identities, append &client_id=<IDENTITY_CLIENT_ID>.263    const identityEndpoint = process.env.IDENTITY_ENDPOINT;264    const url = identityEndpoint265      ? `${identityEndpoint}?api-version=2019-08-01&resource=${AUDIENCE}`266      : `http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=${AUDIENCE}`;267    const headers: Record<string, string> = identityEndpoint268      ? { "X-IDENTITY-HEADER": process.env.IDENTITY_HEADER! }269      : { Metadata: "true" };270    const response = await fetch(url, { headers });271    const body = (await response.json()) as { access_token: string };272    return body.access_token;273  }274275  const client = new Anthropic({276    credentials: oidcFederationProvider({277      identityTokenProvider: fetchEntraToken,278      federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,279      organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,280      serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,281      workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,282      baseURL: "https://api.anthropic.com",283      fetch284    })285  });286287  const message = await client.messages.create({288    model: "claude-opus-5",289    max_tokens: 1024,290    messages: [{ role: "user", content: "Hello from Azure" }]291  });292  for (const block of message.content) {293    if (block.type === "text") {294      console.log(block.text);295    }296  }297  ```298299  ```go Go300  package main301302  import (303  	"context"304  	"encoding/json"305  	"fmt"306  	"net/http"307  	"os"308309  	"github.com/anthropics/anthropic-sdk-go"310  	"github.com/anthropics/anthropic-sdk-go/option"311  )312313  // The audience app registration's identifier URI (see Register the token audience).314  const audience = "api://<APP_ID>"315316  // fetchEntraToken fetches a managed identity token from the platform's token317  // endpoint: IMDS on VMs and VM Scale Sets, or the IDENTITY_ENDPOINT service318  // on App Service, Functions, and Container Apps.319  func fetchEntraToken(ctx context.Context) (string, error) {320  	// With multiple user-assigned identities, append &client_id=<IDENTITY_CLIENT_ID>.321  	tokenURL := "http://169.254.169.254/metadata/identity/oauth2/token" +322  		"?api-version=2018-02-01&resource=" + audience323  	header, value := "Metadata", "true"324  	if endpoint := os.Getenv("IDENTITY_ENDPOINT"); endpoint != "" {325  		tokenURL = endpoint + "?api-version=2019-08-01&resource=" + audience326  		header, value = "X-IDENTITY-HEADER", os.Getenv("IDENTITY_HEADER")327  	}328  	req, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenURL, nil)329  	if err != nil {330  		return "", err331  	}332  	req.Header.Set(header, value)333  	resp, err := http.DefaultClient.Do(req)334  	if err != nil {335  		return "", fmt.Errorf("call token endpoint: %w", err)336  	}337  	defer resp.Body.Close()338  	var body struct {339  		AccessToken string `json:"access_token"`340  	}341  	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {342  		return "", fmt.Errorf("decode token response: %w", err)343  	}344  	return body.AccessToken, nil345  }346347  func main() {348  	client := anthropic.NewClient(349  		option.WithFederationTokenProvider(fetchEntraToken, option.FederationOptions{350  			FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),351  			OrganizationID:   os.Getenv("ANTHROPIC_ORGANIZATION_ID"),352  			ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),353  			WorkspaceID:      os.Getenv("ANTHROPIC_WORKSPACE_ID"),354  		}),355  	)356357  	message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{358  		Model:     anthropic.ModelClaudeOpus5,359  		MaxTokens: 1024,360  		Messages: []anthropic.MessageParam{361  			anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from Azure")),362  		},363  	})364  	if err != nil {365  		panic(err)366  	}367  	for _, block := range message.Content {368  		if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {369  			fmt.Println(textBlock.Text)370  			break371  		}372  	}373  }374  ```375376  ```java Java377  HttpClient http = HttpClient.newHttpClient();378  // The audience app registration's identifier URI (see Register the token audience).379  String audience = "api://<APP_ID>";380  // App Service, Functions, and Container Apps inject IDENTITY_ENDPOINT;381  // VMs and VM Scale Sets use IMDS.382  // With multiple user-assigned identities, append &client_id=<IDENTITY_CLIENT_ID>.383  String identityEndpoint = System.getenv("IDENTITY_ENDPOINT");384  HttpRequest tokenRequest = identityEndpoint != null385          ? HttpRequest.newBuilder(URI.create(identityEndpoint + "?api-version=2019-08-01&resource=" + audience))386                  .header("X-IDENTITY-HEADER", System.getenv("IDENTITY_HEADER"))387                  .build()388          : HttpRequest.newBuilder(URI.create("http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=" + audience))389                  .header("Metadata", "true")390                  .build();391392  IdentityTokenProvider fetchEntraToken = () -> {393      try {394          var response = http.send(tokenRequest, HttpResponse.BodyHandlers.ofString());395          return new ObjectMapper().readTree(response.body()).get("access_token").asText();396      } catch (Exception e) {397          throw new RuntimeException(e);398      }399  };400401  AnthropicClient client = AnthropicOkHttpClient.builder()402          .federationTokenProvider(403                  fetchEntraToken,404                  System.getenv("ANTHROPIC_FEDERATION_RULE_ID"),405                  System.getenv("ANTHROPIC_ORGANIZATION_ID"),406                  System.getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),407                  System.getenv("ANTHROPIC_WORKSPACE_ID"))408          .build();409410  var message = client.messages().create(MessageCreateParams.builder()411          .model(Model.CLAUDE_OPUS_5)412          .maxTokens(1024)413          .addUserMessage("Hello from Azure")414          .build());415416  IO.println(message.content());417  ```418419  ```csharp C#420  using Anthropic.Credentials;421  // ...422423  var credentials = new WorkloadIdentityCredentials(new WorkloadIdentityOptions424  {425      FederationRuleId = Environment.GetEnvironmentVariable("ANTHROPIC_FEDERATION_RULE_ID")!,426      OrganizationId = Environment.GetEnvironmentVariable("ANTHROPIC_ORGANIZATION_ID"),427      ServiceAccountId = Environment.GetEnvironmentVariable("ANTHROPIC_SERVICE_ACCOUNT_ID"),428      WorkspaceId = Environment.GetEnvironmentVariable("ANTHROPIC_WORKSPACE_ID"),429      IdentityTokenProvider = new EntraTokenProvider(),430  });431  using var client = new AnthropicClient(new ClientOptions { Credentials = credentials });432433  var message = await client.Messages.Create(new()434  {435      Model = Model.ClaudeOpus5,436      MaxTokens = 1024,437      Messages = [new() { Role = Role.User, Content = "Hello from Azure" }],438  });439  foreach (var block in message.Content)440  {441      if (block.Value is TextBlock textBlock)442      {443          Console.WriteLine(textBlock.Text);444      }445  }446447  class EntraTokenProvider : IIdentityTokenProvider448  {449      // The audience app registration's identifier URI (see Register the token audience).450      private const string Audience = "api://<APP_ID>";451452      private static readonly HttpClient httpClient = new();453454      public async Task<string> GetIdentityTokenAsync(CancellationToken ct = default)455      {456          // App Service, Functions, and Container Apps inject IDENTITY_ENDPOINT;457          // VMs and VM Scale Sets use IMDS.458          // With multiple user-assigned identities, append &client_id=<IDENTITY_CLIENT_ID>.459          var identityEndpoint = Environment.GetEnvironmentVariable("IDENTITY_ENDPOINT");460          using var request = identityEndpoint is not null461              ? new HttpRequestMessage(HttpMethod.Get,462                  $"{identityEndpoint}?api-version=2019-08-01&resource={Audience}")463              {464                  Headers = { { "X-IDENTITY-HEADER", Environment.GetEnvironmentVariable("IDENTITY_HEADER") } },465              }466              : new HttpRequestMessage(HttpMethod.Get,467                  $"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource={Audience}")468              {469                  Headers = { { "Metadata", "true" } },470              };471          using var response = await httpClient.SendAsync(request, ct);472          response.EnsureSuccessStatusCode();473          using var json = await JsonDocument.ParseAsync(474              await response.Content.ReadAsStreamAsync(ct), default, ct);475          return json.RootElement.GetProperty("access_token").GetString()!;476      }477  }478  ```479480  ```php PHP481  use Anthropic\Client;482  use Anthropic\Credentials\WorkloadIdentityCredentials;483484  // The audience app registration's identifier URI (see Register the token audience).485  const AUDIENCE = 'api://<APP_ID>';486487  function fetchEntraToken(): string488  {489      // App Service, Functions, and Container Apps inject IDENTITY_ENDPOINT;490      // VMs and VM Scale Sets use IMDS.491      // With multiple user-assigned identities, append &client_id=<IDENTITY_CLIENT_ID>.492      $identityEndpoint = getenv('IDENTITY_ENDPOINT');493      if ($identityEndpoint !== false) {494          $url = $identityEndpoint . '?api-version=2019-08-01&resource=' . AUDIENCE;495          $header = 'X-IDENTITY-HEADER: ' . getenv('IDENTITY_HEADER');496      } else {497          $url = 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=' . AUDIENCE;498          $header = 'Metadata: true';499      }500      $context = stream_context_create([501          'http' => ['header' => $header . "\r\n"],502      ]);503      $body = json_decode(file_get_contents($url, false, $context), true);504      return $body['access_token'];505  }506507  $credentials = new WorkloadIdentityCredentials(508      identityTokenProvider: fetchEntraToken(...),509      federationRuleId: getenv('ANTHROPIC_FEDERATION_RULE_ID'),510      organizationId: getenv('ANTHROPIC_ORGANIZATION_ID'),511      serviceAccountId: getenv('ANTHROPIC_SERVICE_ACCOUNT_ID'),512      workspaceId: getenv('ANTHROPIC_WORKSPACE_ID') ?: null,513  );514  $client = new Client(credentials: $credentials);515516  $message = $client->messages->create(517      model: 'claude-opus-5',518      maxTokens: 1024,519      messages: [['role' => 'user', 'content' => 'Hello from Azure']],520  );521  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');522  echo $textBlock->text, PHP_EOL;523  ```524525  ```ruby Ruby526  require "anthropic"527  require "json"528  require "net/http"529530  # The audience app registration's identifier URI (see Register the token audience).531  AUDIENCE = "api://<APP_ID>"532533  def fetch_entra_token534    # App Service, Functions, and Container Apps inject IDENTITY_ENDPOINT;535    # VMs and VM Scale Sets use IMDS.536    # With multiple user-assigned identities, append &client_id=<IDENTITY_CLIENT_ID>.537    if (endpoint = ENV["IDENTITY_ENDPOINT"])538      url = "#{endpoint}?api-version=2019-08-01&resource=#{AUDIENCE}"539      headers = {"X-IDENTITY-HEADER" => ENV.fetch("IDENTITY_HEADER")}540    else541      url = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=#{AUDIENCE}"542      headers = {"Metadata" => "true"}543    end544    response = Net::HTTP.get(URI(url), headers)545    JSON.parse(response).fetch("access_token")546  end547548  credentials = Anthropic::WorkloadIdentityCredentials.new(549    identity_token_provider: -> { fetch_entra_token },550    federation_rule_id: ENV.fetch("ANTHROPIC_FEDERATION_RULE_ID"),551    organization_id: ENV.fetch("ANTHROPIC_ORGANIZATION_ID"),552    service_account_id: ENV.fetch("ANTHROPIC_SERVICE_ACCOUNT_ID"),553    workspace_id: ENV["ANTHROPIC_WORKSPACE_ID"]554  )555  client = Anthropic::Client.new(credentials: credentials)556557  message = client.messages.create(558    model: "claude-opus-5",559    max_tokens: 1024,560    messages: [{role: "user", content: "Hello from Azure"}]561  )562  puts message.content.find { it.type == :text }.text563  ```564565  ```bash CLI566  # Write the Entra-issued access token to a file the CLI can read.567  # Shown for a VM or VM Scale Set (IMDS). On App Service, Functions, or568  # Container Apps, fetch from "$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=api://<APP_ID>"569  # with -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" instead.570  # With multiple user-assigned identities, append &client_id=<IDENTITY_CLIENT_ID>.571  ANTHROPIC_IDENTITY_TOKEN_FILE=$(mktemp)572  trap 'rm -f "$ANTHROPIC_IDENTITY_TOKEN_FILE"' EXIT573  curl -sS -H "Metadata: true" \574    "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=api://<APP_ID>" \575    | jq -r .access_token > "$ANTHROPIC_IDENTITY_TOKEN_FILE"576  export ANTHROPIC_IDENTITY_TOKEN_FILE577578  # ANTHROPIC_FEDERATION_RULE_ID, ANTHROPIC_ORGANIZATION_ID,579  # ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID are read from the environment.580  ant messages create \581    --model claude-opus-5 \582    --max-tokens 1024 \583    --message '{role: user, content: "Hello from Azure"}'584  ```585</CodeGroup>586587### Verify the setup588589From your Azure resource, run the cURL exchange shown in [Acquire and use the token](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#acquire-and-use-the-token) and confirm that `POST /v1/oauth/token` returns a `200` with 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, then decode the Entra token (see [Troubleshoot a failed exchange](https://platform.claude.com/docs/en/manage-claude/wif-reference#troubleshoot-a-failed-exchange) for the command) and check the most common Azure-side causes:590591* **Issuer mismatch:** The registered `issuer_url` must match the token's `iss` claim exactly. A v2.0 token carries `https://login.microsoftonline.com/<TENANT_ID>/v2.0`; if the decoded `ver` claim is `1.0`, see [If your tokens are v1.0](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#if-your-tokens-are-v1-0).592* **Token lifetime:** Managed identity tokens carry up to 24 hours between `iat` and `exp`. If the issuer still has the wizard's `7500` (or the 1-hour default), raise `max_jwt_lifetime_seconds` to `86400` as described in [Configure Anthropic](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#configure-anthropic).593* **Audience mismatch:** The rule's `audience` must equal the token's `aud` exactly: the audience app registration's client ID for the v2.0 tokens this guide configures.594* **Claim name mismatch:** A rule that matches on a claim the token does not carry never passes. v1.0 tokens carry the client ID in `appid`, not `azp`; see [If your tokens are v1.0](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#if-your-tokens-are-v1-0).595596## Use Entra Workload Identity on AKS597598Use this path when your workload runs in an AKS pod. Entra Workload Identity federates a Kubernetes service account with a user-assigned managed identity: Kubernetes projects a service account token (signed by the AKS cluster's OIDC issuer) into the pod at the path in `AZURE_FEDERATED_TOKEN_FILE`. That projected token is not an Entra-issued token, so to stay on the Entra-mediated path described on this page, the workload performs a two-hop exchange: it first redeems the projected token at `https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/token` (federated `client_credentials` grant) for an Entra-issued access token, then passes that Entra token to the Anthropic SDK as the identity token.599600<Tip>601  AKS pods can alternatively skip the Entra exchange and present the Kubernetes-projected service account token to Anthropic directly. That path registers your AKS cluster's OIDC issuer with Anthropic instead of your Entra tenant. See [Use WIF with Kubernetes](https://platform.claude.com/docs/en/manage-claude/wif-providers/kubernetes) for that flow.602</Tip>603604### Configure Entra Workload Identity605606<Steps>607  <Step title="Enable the OIDC issuer and workload identity on your cluster">608    Enabling workload identity installs the `azure-workload-identity` mutating webhook for you; deploy it manually only on non-AKS clusters. Capture the cluster's OIDC issuer URL for the federated credential you create in a later step.609610    ```bash611    az aks update \612      --resource-group <RESOURCE_GROUP> \613      --name <CLUSTER_NAME> \614      --enable-oidc-issuer \615      --enable-workload-identity616617    AKS_OIDC_ISSUER=$(az aks show \618      --resource-group <RESOURCE_GROUP> \619      --name <CLUSTER_NAME> \620      --query oidcIssuerProfile.issuerUrl -o tsv)621    ```622  </Step>623624  <Step title="Create a user-assigned managed identity">625    Capture two values from the identity: the **Client ID** goes into the service account annotation (and is injected into the pod as `AZURE_CLIENT_ID`), and the **Object (principal) ID** appears as the `oid` claim that your Anthropic federation rule matches.626627    ```bash628    az identity create \629      --resource-group <RESOURCE_GROUP> \630      --name claude-inference-identity \631      --location <LOCATION>632633    # Goes in the service account annotation; injected into the pod as AZURE_CLIENT_ID.634    IDENTITY_CLIENT_ID=$(az identity show \635      --resource-group <RESOURCE_GROUP> \636      --name claude-inference-identity \637      --query clientId -o tsv)638639    # Appears as the oid claim that your federation rule matches.640    IDENTITY_OBJECT_ID=$(az identity show \641      --resource-group <RESOURCE_GROUP> \642      --name claude-inference-identity \643      --query principalId -o tsv)644    ```645  </Step>646647  <Step title="Create the annotated Kubernetes service account">648    The `azure-workload-identity` webhook reads the `azure.workload.identity/client-id` annotation to inject `AZURE_CLIENT_ID` into the pod, which the samples in [Acquire and use the token](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#acquire-and-use-the-token-2) read from the environment.649650    ```yaml651    apiVersion: v1652    kind: ServiceAccount653    metadata:654      name: claude-inference655      namespace: inference656      annotations:657        azure.workload.identity/client-id: <IDENTITY_CLIENT_ID>658    ```659  </Step>660661  <Step title="Create the federated credential on the managed identity">662    The federated credential trusts your cluster's OIDC issuer for that specific service account. The `--audience api://AzureADTokenExchange` value is Entra's fixed audience for incoming Kubernetes service account tokens; it is unrelated to the Claude API audience you registered earlier.663664    ```bash665    az identity federated-credential create \666      --resource-group <RESOURCE_GROUP> \667      --identity-name claude-inference-identity \668      --name claude-inference-aks \669      --issuer "$AKS_OIDC_ISSUER" \670      --subject system:serviceaccount:inference:claude-inference \671      --audience api://AzureADTokenExchange672    ```673  </Step>674675  <Step title="Label the pod and set its service account">676    The pod must carry the `azure.workload.identity/use: "true"` label and run as the annotated service account. The webhook then injects `AZURE_FEDERATED_TOKEN_FILE`, `AZURE_CLIENT_ID`, and `AZURE_TENANT_ID` into the pod. The file at `AZURE_FEDERATED_TOKEN_FILE` contains the Kubernetes-projected service account token, signed by the AKS cluster's OIDC issuer.677678    ```yaml679    apiVersion: v1680    kind: Pod681    metadata:682      name: inference-worker683      namespace: inference684      labels:685        azure.workload.identity/use: "true"686    spec:687      serviceAccountName: claude-inference688      containers:689        - name: app690          image: your-registry/inference-worker:latest691    ```692  </Step>693694  <Step title="Decode a sample token">695    The token your Anthropic federation rule sees is not the projected file; it is the Entra-issued token returned by the `client_credentials` exchange. From inside a labeled pod, run step 1 of the cURL sample in [Acquire and use the token](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#acquire-and-use-the-token-2) and decode the result. It carries the same claim shape as the managed identity path:696697    ```json698    {699      "iss": "https://login.microsoftonline.com/<TENANT_ID>/v2.0",700      "sub": "9f8e7d6c-1a2b-3c4d-5e6f-...",701      "aud": "<APP_ID>",702      "oid": "9f8e7d6c-1a2b-3c4d-5e6f-...",703      "tid": "<TENANT_ID>",704      "azp": "<IDENTITY_CLIENT_ID>",705      "ver": "2.0",706      "exp": 1775527120707    }708    ```709710    `sub` and `oid` are the managed identity's object ID, `aud` is the audience app registration's client ID, and `azp` is the managed identity's client ID (the value of `AZURE_CLIENT_ID`). The lifetime differs from the managed identity path: `client_credentials` tokens default to a random 60 to 90 minute window between `iat` and `exp`, not 24 hours.711  </Step>712</Steps>713714### Configure Anthropic715716In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select the **Microsoft Entra** tile. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.717718The 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):719720**Federation issuer:** Choose **v2.0 (login.microsoftonline.com)** in the wizard's **Token issuer** selector. (The selector defaults to v1; that default exists for tenants reusing older registrations that still emit v1.0 tokens.) Entra publishes an OIDC discovery document at the per-tenant issuer URL, so use discovery mode. Each Microsoft Entra tenant you federate needs its own issuer record.721722```json723{724  "name": "azure-prod-tenant",725  "issuer_url": "https://login.microsoftonline.com/<TENANT_ID>/v2.0",726  "jwks": { "type": "discovery" },727  "max_jwt_lifetime_seconds": 7500728}729```730731<Warning>732  The Connect workload wizard's Microsoft Entra tile creates the issuer with `max_jwt_lifetime_seconds` set to `7500` (just over 2 hours), which covers the default 60 to 90 minute lifetime of `client_credentials` tokens. A tenant token-lifetime policy or Continuous Access Evaluation (CAE) can extend that lifetime. If your decoded token's `exp` minus `iat` exceeds 7500 seconds, edit the issuer in **Settings → Workload identity → Issuers** and raise `max_jwt_lifetime_seconds` to match, or exchanges fail with the opaque `401` `authentication_error` response (message `Authentication failed`). If your tenant also runs managed-identity workloads from [Use a managed identity](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#use-a-managed-identity), use that section's `86400` value, which covers both paths.733</Warning>734735A longer accepted lifetime means a leaked Entra token stays exchangeable for longer. If a token leaks, the lever is disabling the federation rule; a tight `oid` match limits which identities can exchange a token in the first place, as described in [Scope your rule](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#scope-your-rule).736737**Federation rule:** Match on the managed identity's object ID and your tenant ID. For the v2.0 tokens this guide configures, the `audience` value is the audience app registration's client ID (the `<APP_ID>` GUID from [Register the token audience](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#register-the-token-audience)). Use the exact `aud` value from your decoded token.738739```json740{741  "name": "azure-inference-worker",742  "issuer_id": "fdis_...",743  "match": {744    "audience": "<APP_ID>",745    "claims": {746      "oid": "9f8e7d6c-1a2b-3c4d-5e6f-...",747      "tid": "<TENANT_ID>"748    }749  },750  "target": {751    "type": "service_account",752    "service_account_id": "svac_..."753  },754  "workspace_id": "wrkspc_...",755  "oauth_scope": "workspace:developer",756  "token_lifetime_seconds": 600757}758```759760`token_lifetime_seconds` is the lifetime of the Anthropic access token the exchange returns, not of the Entra token; the SDK refreshes it for you.761762### Acquire and use the token763764At runtime the pod performs the two-hop exchange: it sends the Kubernetes-projected token (the file at `AZURE_FEDERATED_TOKEN_FILE`) to Entra's token endpoint as a federated `client_credentials` assertion, then exchanges the resulting Entra access token at `POST /v1/oauth/token`. Each Anthropic SDK handles the second exchange and the refresh loop when you supply the Entra fetch as a token-provider callable, as shown in the following examples. The cURL tab shows the raw flow.765766Two different client IDs appear in the samples. `<APP_ID>` is the audience app registration's client ID from [Register the token audience](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#register-the-token-audience); the scope `api://<APP_ID>/.default` asks Entra for a token addressed to that audience. `$AZURE_CLIENT_ID` is the managed identity's client ID, injected by the webhook, and identifies the caller. Do not substitute one for the other.767768<Tip>769  If your workload already uses the Azure Identity client library, pass its token acquisition (`DefaultAzureCredential` with the scope `api://<APP_ID>/.default`) as the identity token provider instead of performing the two-hop exchange yourself. The library reads the same `AZURE_FEDERATED_TOKEN_FILE`, `AZURE_CLIENT_ID`, and `AZURE_TENANT_ID` environment variables and handles the Entra exchange.770</Tip>771772<CodeGroup>773  ```bash cURL774  # 1. Exchange the Kubernetes-projected token (at $AZURE_FEDERATED_TOKEN_FILE)775  #    for an Entra-issued JWT.776  ENTRA_JWT=$(curl -sS "https://login.microsoftonline.com/$AZURE_TENANT_ID/oauth2/v2.0/token" \777    -d grant_type=client_credentials \778    -d "client_id=$AZURE_CLIENT_ID" \779    --data-urlencode "scope=api://<APP_ID>/.default" \780    -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \781    --data-urlencode "client_assertion@$AZURE_FEDERATED_TOKEN_FILE" \782    | jq -r .access_token)783784  # 2. Exchange the Entra JWT for an Anthropic access token.785  ACCESS_TOKEN=$(curl -sS https://api.anthropic.com/v1/oauth/token \786    -H "content-type: application/json" \787    -d @- <<JSON | jq -r .access_token788  {789    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",790    "assertion": "$ENTRA_JWT",791    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",792    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",793    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",794    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"795  }796  JSON797  )798799  # 3. Call the Claude API.800  curl -sS https://api.anthropic.com/v1/messages \801    -H "authorization: Bearer $ACCESS_TOKEN" \802    -H "anthropic-version: 2023-06-01" \803    -H "content-type: application/json" \804    -d '{805      "model": "claude-opus-5",806      "max_tokens": 1024,807      "messages": [{"role": "user", "content": "Hello from Azure"}]808    }' | jq -r '.content[] | select(.type == "text") | .text'809  ```810811  ```python Python812  import os813  from pathlib import Path814815  import anthropic816  import requests817  from anthropic import WorkloadIdentityCredentials818819820  def fetch_entra_token_via_federation() -> str:821      federated_token = Path(os.environ["AZURE_FEDERATED_TOKEN_FILE"]).read_text()822      response = requests.post(823          f"https://login.microsoftonline.com/{os.environ['AZURE_TENANT_ID']}/oauth2/v2.0/token",824          data={825              "client_id": os.environ["AZURE_CLIENT_ID"],826              "grant_type": "client_credentials",827              "scope": "api://<APP_ID>/.default",828              "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",829              "client_assertion": federated_token,830          },831          timeout=5,832      )833      response.raise_for_status()834      return response.json()["access_token"]835836837  client = anthropic.Anthropic(838      credentials=WorkloadIdentityCredentials(839          identity_token_provider=fetch_entra_token_via_federation,840          federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],841          organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],842          service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],843          workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),844      ),845  )846847  message = client.messages.create(848      model="claude-opus-5",849      max_tokens=1024,850      messages=[{"role": "user", "content": "Hello from Azure"}],851  )852  print(next(block.text for block in message.content if block.type == "text"))853  ```854855  ```typescript TypeScript856  import Anthropic from "@anthropic-ai/sdk";857  import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";858  import { readFile } from "node:fs/promises";859860  async function fetchEntraTokenViaFederation(): Promise<string> {861    const federatedToken = await readFile(process.env.AZURE_FEDERATED_TOKEN_FILE!, "utf8");862    const response = await fetch(863      `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/oauth2/v2.0/token`,864      {865        method: "POST",866        headers: { "content-type": "application/x-www-form-urlencoded" },867        body: new URLSearchParams({868          client_id: process.env.AZURE_CLIENT_ID!,869          grant_type: "client_credentials",870          scope: "api://<APP_ID>/.default",871          client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",872          client_assertion: federatedToken873        })874      }875    );876    const body = (await response.json()) as { access_token: string };877    return body.access_token;878  }879880  const client = new Anthropic({881    credentials: oidcFederationProvider({882      identityTokenProvider: fetchEntraTokenViaFederation,883      federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,884      organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,885      serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,886      workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,887      baseURL: "https://api.anthropic.com",888      fetch889    })890  });891892  const message = await client.messages.create({893    model: "claude-opus-5",894    max_tokens: 1024,895    messages: [{ role: "user", content: "Hello from Azure" }]896  });897  for (const block of message.content) {898    if (block.type === "text") {899      console.log(block.text);900    }901  }902  ```903904  ```go Go905  package main906907  import (908  	"context"909  	"encoding/json"910  	"fmt"911  	"net/http"912  	"net/url"913  	"os"914  	"strings"915916  	"github.com/anthropics/anthropic-sdk-go"917  	"github.com/anthropics/anthropic-sdk-go/option"918  )919920  func fetchEntraTokenViaFederation(ctx context.Context) (string, error) {921  	federatedToken, err := os.ReadFile(os.Getenv("AZURE_FEDERATED_TOKEN_FILE"))922  	if err != nil {923  		return "", err924  	}925  	form := url.Values{926  		"client_id":             {os.Getenv("AZURE_CLIENT_ID")},927  		"grant_type":            {"client_credentials"},928  		"scope":                 {"api://<APP_ID>/.default"},929  		"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},930  		"client_assertion":      {strings.TrimSpace(string(federatedToken))},931  	}932  	tokenURL := "https://login.microsoftonline.com/" + os.Getenv("AZURE_TENANT_ID") + "/oauth2/v2.0/token"933  	req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))934  	if err != nil {935  		return "", err936  	}937  	req.Header.Set("content-type", "application/x-www-form-urlencoded")938  	resp, err := http.DefaultClient.Do(req)939  	if err != nil {940  		return "", err941  	}942  	defer resp.Body.Close()943  	var body struct {944  		AccessToken string `json:"access_token"`945  	}946  	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {947  		return "", err948  	}949  	return body.AccessToken, nil950  }951952  func main() {953  	client := anthropic.NewClient(954  		option.WithFederationTokenProvider(option.IdentityTokenFunc(fetchEntraTokenViaFederation), option.FederationOptions{955  			FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),956  			OrganizationID:   os.Getenv("ANTHROPIC_ORGANIZATION_ID"),957  			ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),958  			WorkspaceID:      os.Getenv("ANTHROPIC_WORKSPACE_ID"),959  		}),960  	)961  	message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{962  		Model:     anthropic.ModelClaudeOpus5,963  		MaxTokens: 1024,964  		Messages: []anthropic.MessageParam{965  			anthropic.NewUserMessage(anthropic.NewTextBlock("Hello from Azure")),966  		},967  	})968  	if err != nil {969  		panic(err)970  	}971  	for _, block := range message.Content {972  		if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {973  			fmt.Println(textBlock.Text)974  			break975  		}976  	}977  }978  ```979980  ```java Java981  IdentityTokenProvider fetchEntraTokenViaFederation = () -> {982      try {983          var form = Map.of(984                          "client_id", System.getenv("AZURE_CLIENT_ID"),985                          "grant_type", "client_credentials",986                          "scope", "api://<APP_ID>/.default",987                          "client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",988                          "client_assertion", Files.readString(Path.of(System.getenv("AZURE_FEDERATED_TOKEN_FILE"))))989                  .entrySet().stream()990                  .map(entry -> entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), UTF_8))991                  .collect(Collectors.joining("&"));992          var request = HttpRequest.newBuilder(URI.create(993                          "https://login.microsoftonline.com/" + System.getenv("AZURE_TENANT_ID") + "/oauth2/v2.0/token"))994                  .header("content-type", "application/x-www-form-urlencoded")995                  .POST(HttpRequest.BodyPublishers.ofString(form))996                  .build();997          var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());998          return new ObjectMapper().readTree(response.body()).get("access_token").asText();999      } catch (Exception e) {1000          throw new RuntimeException(e);1001      }1002  };10031004  AnthropicClient client = AnthropicOkHttpClient.builder()1005          .federationTokenProvider(1006                  fetchEntraTokenViaFederation,1007                  System.getenv("ANTHROPIC_FEDERATION_RULE_ID"),1008                  System.getenv("ANTHROPIC_ORGANIZATION_ID"),1009                  System.getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),1010                  System.getenv("ANTHROPIC_WORKSPACE_ID"))1011          .build();10121013  var message = client.messages().create(MessageCreateParams.builder()1014          .model(Model.CLAUDE_OPUS_5)1015          .maxTokens(1024)1016          .addUserMessage("Hello from Azure")1017          .build());10181019  IO.println(message.content());1020  ```10211022  ```csharp C#1023  using Anthropic.Credentials;1024  // ...10251026  var credentials = new WorkloadIdentityCredentials(new WorkloadIdentityOptions1027  {1028      FederationRuleId = Environment.GetEnvironmentVariable("ANTHROPIC_FEDERATION_RULE_ID")!,1029      OrganizationId = Environment.GetEnvironmentVariable("ANTHROPIC_ORGANIZATION_ID"),1030      ServiceAccountId = Environment.GetEnvironmentVariable("ANTHROPIC_SERVICE_ACCOUNT_ID"),1031      WorkspaceId = Environment.GetEnvironmentVariable("ANTHROPIC_WORKSPACE_ID"),1032      IdentityTokenProvider = new EntraFederationTokenProvider(),1033  });1034  using var client = new AnthropicClient(new ClientOptions { Credentials = credentials });10351036  var message = await client.Messages.Create(new()1037  {1038      Model = Model.ClaudeOpus5,1039      MaxTokens = 1024,1040      Messages = [new() { Role = Role.User, Content = "Hello from Azure" }],1041  });1042  foreach (var block in message.Content)1043  {1044      if (block.Value is TextBlock textBlock)1045      {1046          Console.WriteLine(textBlock.Text);1047      }1048  }10491050  class EntraFederationTokenProvider : IIdentityTokenProvider1051  {1052      private static readonly HttpClient Http = new();10531054      public async Task<string> GetIdentityTokenAsync(CancellationToken ct = default)1055      {1056          var federatedToken = await File.ReadAllTextAsync(1057              Environment.GetEnvironmentVariable("AZURE_FEDERATED_TOKEN_FILE")!, ct);1058          var tenantId = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");1059          var form = new FormUrlEncodedContent(new Dictionary<string, string>1060          {1061              ["client_id"] = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID")!,1062              ["grant_type"] = "client_credentials",1063              ["scope"] = "api://<APP_ID>/.default",1064              ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",1065              ["client_assertion"] = federatedToken,1066          });1067          var response = await Http.PostAsync(1068              $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token", form, ct);1069          response.EnsureSuccessStatusCode();1070          using var json = await JsonDocument.ParseAsync(1071              await response.Content.ReadAsStreamAsync(ct), default, ct);1072          return json.RootElement.GetProperty("access_token").GetString()!;1073      }1074  }1075  ```10761077  ```php PHP1078  use Anthropic\Client;1079  use Anthropic\Credentials\WorkloadIdentityCredentials;10801081  function fetchEntraTokenViaFederation(): string1082  {1083      $ch = curl_init('https://login.microsoftonline.com/' . getenv('AZURE_TENANT_ID') . '/oauth2/v2.0/token');1084      curl_setopt_array($ch, [1085          CURLOPT_RETURNTRANSFER => true,1086          CURLOPT_POSTFIELDS => http_build_query([1087              'client_id' => getenv('AZURE_CLIENT_ID'),1088              'grant_type' => 'client_credentials',1089              'scope' => 'api://<APP_ID>/.default',1090              'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',1091              'client_assertion' => file_get_contents(getenv('AZURE_FEDERATED_TOKEN_FILE')),1092          ]),1093      ]);1094      $body = json_decode(curl_exec($ch), true);1095      curl_close($ch);1096      return $body['access_token'];1097  }10981099  $client = new Client(1100      credentials: new WorkloadIdentityCredentials(1101          identityTokenProvider: fetchEntraTokenViaFederation(...),1102          federationRuleId: getenv('ANTHROPIC_FEDERATION_RULE_ID'),1103          organizationId: getenv('ANTHROPIC_ORGANIZATION_ID'),1104          serviceAccountId: getenv('ANTHROPIC_SERVICE_ACCOUNT_ID'),1105          workspaceId: getenv('ANTHROPIC_WORKSPACE_ID') ?: null,1106      ),1107  );11081109  $message = $client->messages->create(1110      model: 'claude-opus-5',1111      maxTokens: 1024,1112      messages: [['role' => 'user', 'content' => 'Hello from Azure']],1113  );1114  $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');1115  echo $textBlock->text, PHP_EOL;1116  ```11171118  ```ruby Ruby1119  require "anthropic"1120  require "json"1121  require "net/http"11221123  def fetch_entra_token_via_federation1124    tenant_id = ENV.fetch("AZURE_TENANT_ID")1125    federated_token = File.read(ENV.fetch("AZURE_FEDERATED_TOKEN_FILE"))1126    response = Net::HTTP.post_form(1127      URI("https://login.microsoftonline.com/#{tenant_id}/oauth2/v2.0/token"),1128      "client_id" => ENV.fetch("AZURE_CLIENT_ID"),1129      "grant_type" => "client_credentials",1130      "scope" => "api://<APP_ID>/.default",1131      "client_assertion_type" => "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",1132      "client_assertion" => federated_token1133    )1134    JSON.parse(response.body).fetch("access_token")1135  end11361137  client = Anthropic::Client.new(1138    credentials: Anthropic::WorkloadIdentityCredentials.new(1139      identity_token_provider: -> { fetch_entra_token_via_federation },1140      federation_rule_id: ENV.fetch("ANTHROPIC_FEDERATION_RULE_ID"),1141      organization_id: ENV.fetch("ANTHROPIC_ORGANIZATION_ID"),1142      service_account_id: ENV.fetch("ANTHROPIC_SERVICE_ACCOUNT_ID"),1143      workspace_id: ENV["ANTHROPIC_WORKSPACE_ID"]1144    )1145  )11461147  message = client.messages.create(1148    model: "claude-opus-5",1149    max_tokens: 1024,1150    messages: [{role: "user", content: "Hello from Azure"}]1151  )1152  puts message.content.find { it.type == :text }.text1153  ```11541155  ```bash CLI1156  # 1. Exchange the Kubernetes-projected token for an Entra-issued access1157  # token and write it to a temp file the CLI can read.1158  ANTHROPIC_IDENTITY_TOKEN_FILE=$(mktemp)1159  trap 'rm -f "$ANTHROPIC_IDENTITY_TOKEN_FILE"' EXIT1160  curl -sS "https://login.microsoftonline.com/$AZURE_TENANT_ID/oauth2/v2.0/token" \1161    -d client_id="$AZURE_CLIENT_ID" \1162    -d grant_type=client_credentials \1163    --data-urlencode "scope=api://<APP_ID>/.default" \1164    -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \1165    --data-urlencode client_assertion@"$AZURE_FEDERATED_TOKEN_FILE" \1166    | jq -r .access_token > "$ANTHROPIC_IDENTITY_TOKEN_FILE"1167  export ANTHROPIC_IDENTITY_TOKEN_FILE11681169  # 2. Call the Claude API. ANTHROPIC_FEDERATION_RULE_ID,1170  # ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID, and ANTHROPIC_WORKSPACE_ID are read1171  # from the environment.1172  ant messages create \1173    --model claude-opus-5 \1174    --max-tokens 1024 \1175    --message '{role: user, content: "Hello from Azure"}'1176  ```1177</CodeGroup>11781179### Verify the setup11801181From inside a labeled pod, run the cURL exchange shown in [Acquire and use the token](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#acquire-and-use-the-token-2) and confirm that `POST /v1/oauth/token` returns a `200` with 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, then decode the Entra-issued token from step 1 (see [Troubleshoot a failed exchange](https://platform.claude.com/docs/en/manage-claude/wif-reference#troubleshoot-a-failed-exchange) for the command) and check the most common Azure-side causes:11821183* **Issuer mismatch:** The registered `issuer_url` must match the token's `iss` claim exactly. A v2.0 token carries `https://login.microsoftonline.com/<TENANT_ID>/v2.0`; if the decoded `ver` claim is `1.0`, see [If your tokens are v1.0](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#if-your-tokens-are-v1-0).1184* **Token lifetime:** If a tenant token-lifetime policy or CAE extends the `client_credentials` token past 7500 seconds, raise the issuer's `max_jwt_lifetime_seconds` as described in [Configure Anthropic](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#configure-anthropic-2).1185* **Audience mismatch:** The rule's `audience` must equal the token's `aud` exactly: the audience app registration's client ID for the v2.0 tokens this guide configures.1186* **Claim name mismatch:** A rule that matches on a claim the token does not carry never passes. v1.0 tokens carry the client ID in `appid`, not `azp`; see [If your tokens are v1.0](https://platform.claude.com/docs/en/manage-claude/wif-providers/azure#if-your-tokens-are-v1-0).11871188## If your tokens are v1.011891190This guide configures the audience app registration with `api.requestedAccessTokenVersion: 2`, so every token it shows is v2.0. If you reuse an existing registration that leaves `requestedAccessTokenVersion` unset, Entra issues v1.0 tokens instead. Decode a sample token and check its `ver` claim; if it is `1.0`, four things change:11911192* **Issuer:** The `iss` claim is `https://sts.windows.net/<TENANT_ID>/` instead of `https://login.microsoftonline.com/<TENANT_ID>/v2.0`. Register the issuer URL exactly as your token's `iss` claim carries it. The two URLs share the same JWKS, so discovery mode works for either.1193* **Wizard selector:** Pick **v1 (sts.windows.net)** in the Connect workload wizard's **Token issuer** selector instead of **v2.0 (login.microsoftonline.com)**.1194* **Audience:** The `aud` claim is the identifier URI you passed as `resource` (for example, `api://<APP_ID>`), not the registration's client ID. Set the federation rule's `audience` to the exact `aud` value from your decoded token.1195* **Client ID claim:** The calling identity's client ID appears in `appid`, not `azp`. The two claims never appear in the same token, so a rule that matches on `azp` never passes against a v1.0 token.11961197The `oid`, `sub`, and `tid` claims carry the same values in both versions, so the rest of this guide applies unchanged.11981199## Scope your rule12001201A federation rule can match the token's subject with `subject_prefix` in addition to (or instead of) the `claims` map; see [Rule matching semantics](https://platform.claude.com/docs/en/manage-claude/wif-reference#rule-matching-semantics) for how the fields combine. Entra `sub` values for these identities are fixed-length canonical GUIDs, so a `subject_prefix` containing the full 36-character object ID matches only that subject; this is a property of Entra's subject format, not of `subject_prefix` in general.12021203<Warning>1204  Every identity in your tenant can request a token for the registered audience, so `audience` and `tid` alone do not identify a specific workload. A rule that omits an `oid` (or `azp`/`appid`) match, or that uses a wildcard or partial-GUID `subject_prefix`, authorizes every managed identity and service principal in the tenant.1205</Warning>12061207Lock the rule's `match` block to the narrowest scope that fits your use case:12081209* **Match `oid` as an exact value:** Set `claims.oid` to the managed identity's full object ID. A `subject_prefix` set to that full object ID is equivalent (the Console wizard sets both); never use a wildcard or partial-GUID `subject_prefix`, which matches more identities than you intend.1210* **Pin `tid` as defense in depth:** The issuer URL already pins your tenant, but adding `claims.tid` guards against configuration drift if the issuer record is later edited.1211* **Pin the audience:** Set `audience` to the exact `aud` value from your decoded token so tokens minted for other applications are rejected.1212* **Use a separate rule for each managed identity:** Create one rule for each identity rather than one rule that authorizes several, so you can revoke a single workload's access without affecting others.12131214## Next steps12151216* Review the full configuration model in [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation).1217* See the [provider guides](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#identity-providers) for AWS, Google Cloud, GitHub Actions, and Kubernetes.1218* For environment variables, profile files, and credential precedence, see the [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference).1219
Files main
Menu

Theme