SPB Git

Repository Public

okta.md 21.5 KB 481 lines markdown

1---2title: Use WIF with Okta3url: https://platform.claude.com/docs/en/manage-claude/wif-providers/okta4description: Federate Okta service application identities to the Claude API with Workload Identity Federation.5---67Okta can act as a workload identity provider by issuing OIDC access tokens to a **service application** through the OAuth 2.0 `client_credentials` grant. Your workload authenticates to Okta (typically with `private_key_jwt`, so no shared secret is stored), receives a signed JSON Web Token (JWT), and exchanges that JWT with Anthropic for a short-lived access token.89The Okta authorization server's issuer URL takes the form `https://<your-domain>.okta.com/oauth2/<auth-server-id>`. If you use the built-in default server, the path is `/oauth2/default`.1011<Note>12  You must use an Okta **custom authorization server** (including the `default` one). Tokens issued directly by the Okta org authorization server (the `/oauth2/v1/token` endpoint with no authorization server ID in the path) cannot be validated by external parties because Okta does not publish signing keys for them.13</Note>1415There are many ways to configure and authenticate to Okta that are outside the scope of this documentation. Ensure that your configuration and authentication mechanisms follow your company's guidance and security practices.1617## Prerequisites1819* Familiarity with [WIF concepts](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#concepts): service accounts, federation issuers, and federation rules.20* An Okta organization with API Access Management enabled (required for custom authorization servers).21* Permission to create service accounts, federation issuers, and federation rules in the Claude Console for your Anthropic organization.22* A workload that can request a token from Okta's `/v1/token` endpoint and reach `api.anthropic.com`.2324## Configure Okta2526At a high level you need to:27281. Create an Okta service application.292. Configure your default authorization server (or create a new custom authorization server) with an audience, a scope, an access policy, and any custom claims you want to match on.3031The exact navigation depends on your Okta org configuration and admin console version. The following numbered steps walk through one common path:32331. **Create a service app integration.** In the Okta Admin Console, create a new app integration of type **API Services** (OIDC, machine-to-machine). Note the generated **Client ID**.342. **Configure client authentication.** For a keyless setup, choose **Public key / Private key** (`private_key_jwt`) and register your workload's public JWK. Alternatively, use a client secret if your environment can store one securely. For the following example you may need to disable the DPoP requirement on the application; ensure that your production setup adheres to your organization's security requirements.353. **Set the audience.** On your custom authorization server, set the audience to `https://api.anthropic.com` so issued access tokens carry that `aud` claim. Anthropic validates `aud` against this fixed value.364. **Grant a scope.** On your custom authorization server, ensure at least one scope exists that the service app is allowed to request (for example, `anthropic.access`). Okta rejects `client_credentials` requests that do not include a granted scope.375. **Create an access policy.** On your custom authorization server, create an access policy with at least one rule that allows your service app to request the scope you granted in step 4.386. **(Optional) Add custom claims.** If you want to match on something other than the client ID, add a claim to the access token in your authorization server's **Claims** tab.3940For a service app using `client_credentials`, Okta sets the `sub` claim of the issued access token to the application's **Client ID**, and `iss` to the authorization server's issuer URL.4142## Configure Anthropic4344In the Claude Console, open **Settings → Workload identity**, click **Connect workload**, and select **Custom OIDC**. The wizard walks you through registering the issuer, creating a service account, and creating a federation rule.4546The 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):4748**Federation issuer:** Use your Okta custom authorization server URL and discovery mode. Anthropic reads Okta's `.well-known/openid-configuration` discovery document and fetches the JWKS from the `jwks_uri` it advertises.4950```json51{52  "name": "okta-prod",53  "issuer_url": "https://acme.okta.com/oauth2/aus1a2b3c4d5e6f7g8h9",54  "jwks": { "type": "discovery" }55}56```5758**Federation rule:** Match on the Okta `sub` claim, which is the service app's Client ID. If you defined custom claims in Okta, you can match on those instead with the `claims` map or a CEL `condition`.5960```json61{62  "name": "okta-pipeline",63  "issuer_id": "fdis_...",64  "match": {65    "subject_prefix": "0oa1b2c3d4e5f6g7h8i9",66    "audience": "https://api.anthropic.com"67  },68  "target": { "type": "service_account", "service_account_id": "svac_..." },69  "workspace_id": "wrkspc_...",70  "oauth_scope": "workspace:developer",71  "token_lifetime_seconds": 60072}73```7475## Acquire a token and call the Claude API7677Unlike platform-native providers (AWS, Google Cloud, Kubernetes), which make a token available inside the workload's runtime (through a projected file or local metadata endpoint), Okta does not. Your workload must call Okta's token endpoint to obtain a JWT, then pass that JWT to the Anthropic SDK as the identity token.7879<CodeGroup>80  ```bash cURL81  # 1. Request an access token from Okta (client_credentials with private_key_jwt).82  OKTA_JWT=$(curl -sS "https://acme.okta.com/oauth2/aus1a2b3c4d5e6f7g8h9/v1/token" \83    -d grant_type=client_credentials \84    -d scope=anthropic.access \85    -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \86    --data-urlencode client_assertion="$SIGNED_CLIENT_ASSERTION" \87    | jq -r .access_token)8889  # 2. Exchange the Okta JWT for an Anthropic access token.90  ACCESS_TOKEN=$(curl -sS https://api.anthropic.com/v1/oauth/token \91    -H "content-type: application/json" \92    -d @- <<JSON | jq -r .access_token93  {94    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",95    "assertion": "$OKTA_JWT",96    "federation_rule_id": "$ANTHROPIC_FEDERATION_RULE_ID",97    "organization_id": "$ANTHROPIC_ORGANIZATION_ID",98    "service_account_id": "$ANTHROPIC_SERVICE_ACCOUNT_ID",99    "workspace_id": "$ANTHROPIC_WORKSPACE_ID"100  }101  JSON102  )103104  # 3. Call the Claude API.105  curl https://api.anthropic.com/v1/messages \106    -H "authorization: Bearer $ACCESS_TOKEN" \107    -H "anthropic-version: 2023-06-01" \108    -H "content-type: application/json" \109    -d '{"model": "claude-opus-5", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello, Claude"}]}' \110    | jq -r '.content[] | select(.type == "text") | .text'111  ```112113  ```python Python114  import os115  import httpx2116  import anthropic117  from anthropic import WorkloadIdentityCredentials118119120  def fetch_okta_token() -> str:121      response = httpx2.post(122          f"{os.environ['OKTA_ISSUER']}/v1/token",123          data={124              "grant_type": "client_credentials",125              "scope": "anthropic.access",126              "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",127              # Build the RFC 7523 client_assertion JWT signed with your Okta app's private key128              "client_assertion": build_signed_client_assertion(),129          },130      )131      response.raise_for_status()132      return response.json()["access_token"]133134135  client = anthropic.Anthropic(136      credentials=WorkloadIdentityCredentials(137          identity_token_provider=fetch_okta_token,138          federation_rule_id=os.environ["ANTHROPIC_FEDERATION_RULE_ID"],139          organization_id=os.environ["ANTHROPIC_ORGANIZATION_ID"],140          service_account_id=os.environ["ANTHROPIC_SERVICE_ACCOUNT_ID"],141          workspace_id=os.environ.get("ANTHROPIC_WORKSPACE_ID"),142      ),143  )144145  message = client.messages.create(146      model="claude-opus-5",147      max_tokens=1024,148      messages=[{"role": "user", "content": "Hello, Claude"}],149  )150  print(next(block.text for block in message.content if block.type == "text"))151  ```152153  ```typescript TypeScript154  import Anthropic from "@anthropic-ai/sdk";155  import { oidcFederationProvider } from "@anthropic-ai/sdk/lib/credentials/oidc-federation";156157  async function fetchOktaToken(): Promise<string> {158    const response = await fetch(`${process.env.OKTA_ISSUER}/v1/token`, {159      method: "POST",160      headers: { "content-type": "application/x-www-form-urlencoded" },161      body: new URLSearchParams({162        grant_type: "client_credentials",163        scope: "anthropic.access",164        client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",165        // Build the RFC 7523 client_assertion JWT signed with your Okta app's private key166        client_assertion: buildSignedClientAssertion()167      })168    });169    const body = (await response.json()) as { access_token: string };170    return body.access_token;171  }172173  const client = new Anthropic({174    credentials: oidcFederationProvider({175      identityTokenProvider: fetchOktaToken,176      federationRuleId: process.env.ANTHROPIC_FEDERATION_RULE_ID!,177      organizationId: process.env.ANTHROPIC_ORGANIZATION_ID!,178      serviceAccountId: process.env.ANTHROPIC_SERVICE_ACCOUNT_ID,179      workspaceId: process.env.ANTHROPIC_WORKSPACE_ID,180      baseURL: "https://api.anthropic.com",181      fetch182    })183  });184185  const message = await client.messages.create({186    model: "claude-opus-5",187    max_tokens: 1024,188    messages: [{ role: "user", content: "Hello, Claude" }]189  });190  for (const block of message.content) {191    if (block.type === "text") {192      console.log(block.text);193    }194  }195  ```196197  ```go Go198  package main199200  import (201  	"context"202  	"encoding/json"203  	"fmt"204  	"net/http"205  	"net/url"206  	"os"207  	"strings"208209  	"github.com/anthropics/anthropic-sdk-go"210  	"github.com/anthropics/anthropic-sdk-go/option"211  )212213  func fetchOktaToken(ctx context.Context) (string, error) {214  	form := url.Values{215  		"grant_type":            {"client_credentials"},216  		"scope":                 {"anthropic.access"},217  		"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},218  		// Build the RFC 7523 client_assertion JWT signed with your Okta app's private key219  		"client_assertion": {buildSignedClientAssertion()},220  	}221  	req, err := http.NewRequestWithContext(ctx, http.MethodPost,222  		os.Getenv("OKTA_ISSUER")+"/v1/token", strings.NewReader(form.Encode()))223  	if err != nil {224  		return "", err225  	}226  	req.Header.Set("content-type", "application/x-www-form-urlencoded")227  	resp, err := http.DefaultClient.Do(req)228  	if err != nil {229  		return "", err230  	}231  	defer resp.Body.Close()232  	var body struct {233  		AccessToken string `json:"access_token"`234  	}235  	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {236  		return "", err237  	}238  	return body.AccessToken, nil239  }240241  func main() {242  	client := anthropic.NewClient(243  		option.WithFederationTokenProvider(option.IdentityTokenFunc(fetchOktaToken), option.FederationOptions{244  			FederationRuleID: os.Getenv("ANTHROPIC_FEDERATION_RULE_ID"),245  			OrganizationID:   os.Getenv("ANTHROPIC_ORGANIZATION_ID"),246  			ServiceAccountID: os.Getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"),247  			WorkspaceID:      os.Getenv("ANTHROPIC_WORKSPACE_ID"),248  		}),249  	)250  	message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{251  		Model:     anthropic.ModelClaudeOpus5,252  		MaxTokens: 1024,253  		Messages: []anthropic.MessageParam{254  			anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),255  		},256  	})257  	if err != nil {258  		panic(err)259  	}260  	for _, block := range message.Content {261  		if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {262  			fmt.Println(textBlock.Text)263  			break264  		}265  	}266  }267  ```268269  ```java Java270  IdentityTokenProvider fetchOktaToken = () -> {271      try {272          var form = Map.of(273                          "grant_type", "client_credentials",274                          "scope", "anthropic.access",275                          "client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",276                          // Build the RFC 7523 client_assertion JWT signed with your Okta app's private key277                          "client_assertion", buildSignedClientAssertion())278                  .entrySet().stream()279                  .map(entry -> entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), UTF_8))280                  .collect(Collectors.joining("&"));281          var request = HttpRequest.newBuilder(URI.create(System.getenv("OKTA_ISSUER") + "/v1/token"))282                  .header("content-type", "application/x-www-form-urlencoded")283                  .POST(HttpRequest.BodyPublishers.ofString(form))284                  .build();285          var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());286          return new ObjectMapper().readTree(response.body()).get("access_token").asText();287      } catch (Exception e) {288          throw new RuntimeException(e);289      }290  };291292  AnthropicClient client = AnthropicOkHttpClient.builder()293          .federationTokenProvider(294                  fetchOktaToken,295                  System.getenv("ANTHROPIC_FEDERATION_RULE_ID"),296                  System.getenv("ANTHROPIC_ORGANIZATION_ID"),297                  System.getenv("ANTHROPIC_SERVICE_ACCOUNT_ID"))298          .build();299300  var message = client.messages().create(MessageCreateParams.builder()301          .model(Model.CLAUDE_OPUS_5)302          .maxTokens(1024)303          .addUserMessage("Hello, Claude")304          .build());305306  IO.println(message.content());307  ```308309  ```csharp C#310  using Anthropic.Credentials;311  // ...312313  var credentials = new WorkloadIdentityCredentials(new WorkloadIdentityOptions314  {315      FederationRuleId = Environment.GetEnvironmentVariable("ANTHROPIC_FEDERATION_RULE_ID")!,316      OrganizationId = Environment.GetEnvironmentVariable("ANTHROPIC_ORGANIZATION_ID"),317      ServiceAccountId = Environment.GetEnvironmentVariable("ANTHROPIC_SERVICE_ACCOUNT_ID"),318      WorkspaceId = Environment.GetEnvironmentVariable("ANTHROPIC_WORKSPACE_ID"),319      IdentityTokenProvider = new OktaTokenProvider(),320  });321  using var client = new AnthropicClient(new ClientOptions { Credentials = credentials });322323  var message = await client.Messages.Create(new()324  {325      Model = Model.ClaudeOpus5,326      MaxTokens = 1024,327      Messages = [new() { Role = Role.User, Content = "Hello, Claude" }],328  });329  foreach (var block in message.Content)330  {331      if (block.Value is TextBlock textBlock)332      {333          Console.WriteLine(textBlock.Text);334      }335  }336337  class OktaTokenProvider : IIdentityTokenProvider338  {339      private static readonly HttpClient Http = new();340341      public async Task<string> GetIdentityTokenAsync(CancellationToken ct = default)342      {343          var form = new FormUrlEncodedContent(new Dictionary<string, string>344          {345              ["grant_type"] = "client_credentials",346              ["scope"] = "anthropic.access",347              ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",348              // Build the RFC 7523 client_assertion JWT signed with your Okta app's private key349              ["client_assertion"] = BuildSignedClientAssertion(),350          });351          var response = await Http.PostAsync(352              $"{Environment.GetEnvironmentVariable("OKTA_ISSUER")}/v1/token", form, ct);353          response.EnsureSuccessStatusCode();354          using var json = await JsonDocument.ParseAsync(355              await response.Content.ReadAsStreamAsync(ct), default, ct);356          return json.RootElement.GetProperty("access_token").GetString()!;357      }358  }359  ```360361  ```bash CLI362  # 1. Request an access token from Okta and write it to a temp file.363  ANTHROPIC_IDENTITY_TOKEN_FILE=$(mktemp)364  curl -sS "$OKTA_ISSUER/v1/token" \365    -d grant_type=client_credentials \366    -d scope=anthropic.access \367    -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \368    --data-urlencode client_assertion="$SIGNED_CLIENT_ASSERTION" \369    | jq -r .access_token > "$ANTHROPIC_IDENTITY_TOKEN_FILE"370  export ANTHROPIC_IDENTITY_TOKEN_FILE371372  # 2. Call the Claude API. The CLI reads ANTHROPIC_FEDERATION_RULE_ID,373  # ANTHROPIC_ORGANIZATION_ID, ANTHROPIC_SERVICE_ACCOUNT_ID, ANTHROPIC_WORKSPACE_ID, and374  # ANTHROPIC_IDENTITY_TOKEN_FILE and performs the exchange.375  ant messages create \376    --model claude-opus-5 \377    --max-tokens 1024 \378    --message '{role: user, content: "Hello, Claude"}'379  ```380381  ```php PHP382  use Anthropic\Client;383  use Anthropic\Credentials\WorkloadIdentityCredentials;384385  function fetchOktaToken(): string386  {387      $ch = curl_init(getenv('OKTA_ISSUER') . '/v1/token');388      curl_setopt_array($ch, [389          CURLOPT_RETURNTRANSFER => true,390          CURLOPT_POSTFIELDS => http_build_query([391              'grant_type' => 'client_credentials',392              'scope' => 'anthropic.access',393              'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',394              // Build the RFC 7523 client_assertion JWT signed with your Okta app's private key395              'client_assertion' => buildSignedClientAssertion(),396          ]),397      ]);398      $body = json_decode(curl_exec($ch), true);399      curl_close($ch);400      return $body['access_token'];401  }402403  $client = new Client(404      credentials: new WorkloadIdentityCredentials(405          identityTokenProvider: fetchOktaToken(...),406          federationRuleId: getenv('ANTHROPIC_FEDERATION_RULE_ID'),407          organizationId: getenv('ANTHROPIC_ORGANIZATION_ID'),408          serviceAccountId: getenv('ANTHROPIC_SERVICE_ACCOUNT_ID'),409          workspaceId: getenv('ANTHROPIC_WORKSPACE_ID') ?: null,410      ),411  );412413  $message = $client->messages->create(414      model: 'claude-opus-5',415      maxTokens: 1024,416      messages: [['role' => 'user', 'content' => 'Hello, Claude']],417  );418  echo array_find($message->content, static fn ($block): bool => $block->type === 'text')->text, PHP_EOL;419  ```420421  ```ruby Ruby422  require "anthropic"423  require "json"424  require "net/http"425426  def fetch_okta_token427    uri = URI("#{ENV.fetch('OKTA_ISSUER')}/v1/token")428    response = Net::HTTP.post_form(429      uri,430      "grant_type" => "client_credentials",431      "scope" => "anthropic.access",432      "client_assertion_type" => "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",433      # Build the RFC 7523 client_assertion JWT signed with your Okta app's private key434      "client_assertion" => build_signed_client_assertion435    )436    JSON.parse(response.body).fetch("access_token")437  end438439  client = Anthropic::Client.new(440    credentials: Anthropic::WorkloadIdentityCredentials.new(441      identity_token_provider: -> { fetch_okta_token },442      federation_rule_id: ENV.fetch("ANTHROPIC_FEDERATION_RULE_ID"),443      organization_id: ENV.fetch("ANTHROPIC_ORGANIZATION_ID"),444      service_account_id: ENV.fetch("ANTHROPIC_SERVICE_ACCOUNT_ID"),445      workspace_id: ENV["ANTHROPIC_WORKSPACE_ID"]446    )447  )448449  message = client.messages.create(450    model: "claude-opus-5",451    max_tokens: 1024,452    messages: [{role: "user", content: "Hello, Claude"}]453  )454  puts message.content.find { it.type == :text }.text455  ```456</CodeGroup>457458Each SDK tab shows the callable pattern: the Anthropic SDK calls your identity-token provider again whenever the Anthropic access token approaches expiry, so your Okta fetcher should return a fresh token on each call rather than caching one indefinitely. The `ant` CLI re-reads `ANTHROPIC_IDENTITY_TOKEN_FILE` on each exchange, so refresh that file on a timer for long-running shells.459460## Verify the setup461462A successful exchange returns an `access_token` beginning with `sk-ant-oat01-` and an `expires_in` value in seconds. If the exchange fails with the opaque `401` `authentication_error` response (message `Authentication failed`), check the [authentication history page](https://platform.claude.com/settings/workload-identity-federation?tab=history) for the deny reason and see [Troubleshoot a failed exchange](https://platform.claude.com/docs/en/manage-claude/wif-reference#troubleshoot-a-failed-exchange); the most common Okta-side cause is an `issuer_url` mismatch (it must include the `/oauth2/<auth-server-id>` path; the Okta org authorization server is not usable).463464## Scope your rule465466<Warning>467  Multiple service apps under the same Okta authorization server share the same issuer. A rule that omits `subject_prefix` matches every service app on that server, so any team that can register one could obtain a federated Anthropic token.468</Warning>469470Lock the rule's `match` block to the narrowest scope that fits your use case:471472* **Pin the exact Client ID:** Set `subject_prefix` to the service app's full Client ID with no trailing `*`.473* **Pin the audience:** Match the `audience` value you configured on the authorization server so tokens minted for a different audience are rejected.474* **Match on custom claims:** For finer-grained scoping, add claims in the authorization server's **Claims** tab and match them with the rule's `claims` map or a CEL `condition`.475* **Use one rule per service app:** Create a separate federation rule for each service app rather than sharing one rule across apps.476477## Next steps478479* Review the [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference) for the full credential resolution order and profile configuration.480* See the [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference#rule-matching-semantics) to match on custom Okta claims with CEL expressions.481
Files main
Menu

Theme