SPB Git

Repository Public

authentication.md 24.4 KB 392 lines markdown

1---2title: Authentication3url: https://platform.claude.com/docs/en/manage-claude/authentication4description: Authenticate to the Claude API with API keys, Workload Identity Federation, or App Attest.5---67The Claude API supports three ways to authenticate requests:89| Method                                                                                                                        | Credential                                                                                              | Best for                                                                                                                                        |10| ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |11| [API key](https://platform.claude.com/docs/en/manage-claude/authentication#api-keys)                                          | Static `sk-ant-api...` secret sent as a bearer token in the `Authorization` header                      | Local development, prototyping, scripts, and servers where you control secret storage                                                           |12| [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/authentication#workload-identity-federation) | Short-lived bearer token exchanged from your identity provider's identity token                         | Production workloads on cloud platforms (AWS, Google Cloud, Azure), CI/CD pipelines, and Kubernetes, where you want to eliminate static secrets |13| [App Attest](https://platform.claude.com/docs/en/manage-claude/authentication#app-attest)                                     | Short-lived access token issued to a genuine, attested installation of your registered iOS or macOS app | iOS and macOS apps distributed to end users, where the app calls the Claude API directly with no back end or proxy                              |1415API keys and Workload Identity Federation grant the same access to Claude API endpoints. Choose API keys to get started quickly: a personal key for your own development, or a service account key for anything shared. Move to Workload Identity Federation when your workload already has a platform-issued identity you can federate. Use App Attest for iOS and macOS apps you distribute to end users.1617## API keys1819API keys are static secrets that you generate in the Claude Console and send on every request as a bearer token in the `Authorization` header.2021### Key types2223When you create a key, you choose its type, which determines what the key can do, where it works, and when it stops working:2425| Key type                   | Acts as                                                                                                              | Works in                                                                                                                                                                                              | Stops working when                                                                                                                                                                                                                   |26| -------------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |27| **Personal key**           | You, the user, with your roles and permissions                                                                       | Either a single workspace or the workspaces where your role allows API use, chosen when the key is created                                                                                            | You lose access to the organization or, for a single-workspace key, to that workspace. Personal keys are archived when you are removed from the organization. If you are re-invited, create new keys; archived keys are not restored |28| **Service account key**    | A [service account](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#service-accounts) | Either a single workspace or anything the service account has access to, chosen when the key is created. A service account has access to the Default Workspace and to workspaces it has been added to | The service account is archived or, for a single-workspace key, is removed from that workspace                                                                                                                                       |29| **Workspace key** (legacy) | No one: it belongs to the workspace it was created in                                                                | That workspace                                                                                                                                                                                        | It expires, is disabled or deleted, or its workspace is archived, regardless of whether its creator leaves the organization                                                                                                          |3031Personal keys and service account keys are identity-backed: each belongs to a user or service account your organization already manages, and every request acts as that identity. When that identity is removed from the organization, the key stops working. This means that keys won't accidentally outlive the people or workloads that own them. Prefer them over workspace keys for new integrations.3233Use a personal key for your own development and scripts. A shared personal key acts as one person and breaks when they leave. For shared or automated workloads (CI, production services), have an organization admin create a service account so the workload has its own identity.3435Workspace API keys still work but should be considered legacy; identity-backed keys or [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) are preferred. To migrate, see [Replacing workspace API keys](https://platform.claude.com/docs/en/manage-claude/authentication#replacing-workspace-api-keys).3637### Create and use a key3839* **Create a key:** Go to [Settings → API keys](https://platform.claude.com/settings/keys) in the Claude Console and click **Create key**. Name the key and choose an [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration). Set **Linked account** to yourself for a personal key, or to a service account for a key shared across multiple users. You can also scope the key to a specific workspace, which lets you skip setting a workspace ID manually in future requests.40* **Use the key:** Send it as `Authorization: Bearer <key>` on direct HTTP requests, or set the `ANTHROPIC_API_KEY` environment variable and the [client SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) pick it up automatically.4142```http43POST /v1/messages44Authorization: Bearer YOUR_API_KEY45anthropic-version: 2023-06-0146content-type: application/json47```4849The legacy `x-api-key: YOUR_API_KEY` header is still supported in place of `Authorization`.5051Store API keys in a secrets manager, rotate them periodically, and disable or delete any key you suspect has leaked. On the [API keys page](https://platform.claude.com/settings/keys), **Disable** is reversible (the Admin API reports the key's `status` as `"inactive"`, and **Re-enable** returns it to `"active"`), while **Delete** is permanent: the key is archived and still appears in [List API Keys](https://platform.claude.com/docs/en/api/admin/api_keys/list) with `status: "archived"`. Expired keys can only be deleted. You can also set an [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration) when you create a key to limit how long a leaked credential stays usable.5253<CodeGroup>54  ```bash cURL55  curl https://api.anthropic.com/v1/messages \56    -H "x-api-key: $ANTHROPIC_API_KEY" \57    -H "anthropic-version: 2023-06-01" \58    -H "content-type: application/json" \59    -d '{60      "model": "claude-opus-5",61      "max_tokens": 1024,62      "messages": [{"role": "user", "content": "Hello, Claude"}]63    }'64  ```6566  ```python Python67  client = Anthropic(api_key="my-anthropic-api-key")68  # or, with ANTHROPIC_API_KEY set in the environment:69  client = Anthropic()70  ```7172  ```typescript TypeScript73  const client = new Anthropic({ apiKey: "my-anthropic-api-key" });74  // or, with ANTHROPIC_API_KEY set in the environment:75  // const client = new Anthropic();76  ```7778  ```go Go79  client := anthropic.NewClient(80  	option.WithAPIKey("sk-ant-api03-..."), // defaults to os.LookupEnv("ANTHROPIC_API_KEY")81  )82  ```8384  ```java Java85  import com.anthropic.client.AnthropicClient;86  import com.anthropic.client.okhttp.AnthropicOkHttpClient;8788  // Explicit89  AnthropicClient client = AnthropicOkHttpClient.builder()90    .apiKey("my-anthropic-api-key")91    .build();9293  // From ANTHROPIC_API_KEY (or anthropic.apiKey system property)94  AnthropicClient clientFromEnv = AnthropicOkHttpClient.fromEnv();95  ```9697  ```csharp C#98  using Anthropic;99100  AnthropicClient client = new() { ApiKey = "my-anthropic-api-key" };101  // Or, with ANTHROPIC_API_KEY set in the environment:102  // AnthropicClient client = new();103  ```104105  ```php PHP106  // Reads ANTHROPIC_API_KEY from the environment107  $client = new Client();108  // Or pass the key explicitly:109  $client = new Client(apiKey: 'my-anthropic-api-key');110  ```111112  ```ruby Ruby113  anthropic = Anthropic::Client.new(api_key: "my-anthropic-api-key")114  # or, with ANTHROPIC_API_KEY set in the environment:115  anthropic = Anthropic::Client.new116  ```117118  ```bash CLI119  # See /docs/en/cli-sdks-libraries/cli/authentication#api-key for zsh, bash, and Windows variants120  export ANTHROPIC_API_KEY=sk-ant-api03-...121  ```122</CodeGroup>123124### Select a workspace125126API keys that are created for a specific workspace only work in that workspace, and API requests using these keys can omit the workspace ID.127128If your API key isn't scoped to a workspace, you must specify the workspace ID in the `anthropic-workspace-id` header for each request. See the following example for how to set this header in a request or in SDKs.129130The [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) accepts a personal key or service account key only if the key isn't scoped to a specific workspace.131132You can find a workspace's ID in the **ID** column of [Settings → Workspaces](https://platform.claude.com/settings/workspaces) in the Claude Console, or by calling the [List Workspaces](https://platform.claude.com/docs/en/api/admin/workspaces/list) endpoint. List Workspaces omits the Default Workspace; its ID is in the `anthropic-workspace-id` [response header](https://platform.claude.com/docs/en/manage-claude/workspaces#identify-the-workspace-behind-an-api-response) of any request that runs there.133134<CodeGroup>135  ```bash cURL136  # Required on every request for a multi-workspace key.137  # Omit the anthropic-workspace-id header for a single-workspace key.138  curl https://api.anthropic.com/v1/messages \139    -H "x-api-key: $ANTHROPIC_API_KEY" \140    -H "anthropic-version: 2023-06-01" \141    -H "anthropic-workspace-id: wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ" \142    -H "content-type: application/json" \143    -d '{144      "model": "claude-opus-5",145      "max_tokens": 1024,146      "messages": [{"role": "user", "content": "Hello, Claude"}]147    }'148  ```149150  ```bash CLI151  # Required on every command for a multi-workspace key.152  # Omit --workspace-id for a single-workspace key.153  ant messages create \154    --workspace-id wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ \155    --model claude-opus-5 \156    --max-tokens 1024 \157    --message '{role: user, content: "Hello, Claude"}'158  ```159160  ```python Python161  client = Anthropic()  # reads ANTHROPIC_API_KEY162163  # Required on every request for a multi-workspace key.164  # Omit extra_headers for a single-workspace key.165  message = client.messages.create(166      model="claude-opus-5",167      max_tokens=1024,168      messages=[{"role": "user", "content": "Hello, Claude"}],169      extra_headers={"anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"},170  )171  print(message.content)172173  # Or set it once for every request from this client:174  workspace_client = Anthropic(175      default_headers={"anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"},176  )177  ```178179  ```typescript TypeScript180  const client = new Anthropic(); // reads ANTHROPIC_API_KEY181182  // Required on every request for a multi-workspace key.183  // Omit the second argument for a single-workspace key.184  const message = await client.messages.create(185    {186      model: "claude-opus-5",187      max_tokens: 1024,188      messages: [{ role: "user", content: "Hello, Claude" }]189    },190    { headers: { "anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ" } }191  );192  console.log(message.content);193194  // Or set it once for every request from this client:195  const workspaceClient = new Anthropic({196    defaultHeaders: { "anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ" }197  });198  ```199200  ```csharp C#201  AnthropicClient client = new(); // reads ANTHROPIC_API_KEY202203  MessageCreateParams parameters = new()204  {205      Model = Model.ClaudeOpus5,206      MaxTokens = 1024,207      Messages = [new() { Role = Role.User, Content = "Hello, Claude" }],208  };209210  // Required on every request for a multi-workspace key.211  // Call client.Messages.Create(parameters) directly for a single-workspace key.212  var message = await client213      .WithOptions(options =>214          options with215          {216              ExtraHeaders = new Dictionary<string, string>217              {218                  ["anthropic-workspace-id"] = "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ",219              },220          }221      )222      .Messages.Create(parameters);223  Console.WriteLine(message);224225  // Or set it once for every request from this client:226  AnthropicClient workspaceClient = new(new ClientOptions227  {228      ExtraHeaders = new Dictionary<string, string>229      {230          ["anthropic-workspace-id"] = "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ",231      },232  });233  ```234235  ```go Go236  client := anthropic.NewClient() // reads ANTHROPIC_API_KEY237238  // Required on every request for a multi-workspace key.239  // Omit the option for a single-workspace key.240  message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{241  	Model:     anthropic.ModelClaudeOpus5,242  	MaxTokens: 1024,243  	Messages: []anthropic.MessageParam{244  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),245  	},246  }, option.WithHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"))247  if err != nil {248  	log.Fatal(err)249  }250  fmt.Println(message.Content)251252  // Or set it once for every request from this client:253  workspaceClient := anthropic.NewClient(254  	option.WithHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"),255  )256  ```257258  ```java Java259  AnthropicClient client = AnthropicOkHttpClient.fromEnv(); // reads ANTHROPIC_API_KEY260261  // Required on every request for a multi-workspace key.262  // Omit putAdditionalHeader for a single-workspace key.263  Message message = client.messages().create(MessageCreateParams.builder()264      .model(Model.CLAUDE_OPUS_5)265      .maxTokens(1024)266      .addUserMessage("Hello, Claude")267      .putAdditionalHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ")268      .build());269270  IO.println(message.content());271272  // Or set it once for every request from this client:273  AnthropicClient workspaceClient = AnthropicOkHttpClient.builder()274      .fromEnv()275      .putHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ")276      .build();277  ```278279  ```php PHP280  $client = new Client(); // reads ANTHROPIC_API_KEY281282  // Required on every request for a multi-workspace key.283  // Omit requestOptions for a single-workspace key.284  $message = $client->messages->create(285      model: Model::CLAUDE_OPUS_5,286      maxTokens: 1024,287      messages: [['role' => 'user', 'content' => 'Hello, Claude']],288      requestOptions: [289          'extraHeaders' => ['anthropic-workspace-id' => 'wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ'],290      ],291  );292293  echo json_encode($message->content), PHP_EOL;294  ```295296  ```ruby Ruby297  client = Anthropic::Client.new # reads ANTHROPIC_API_KEY298299  # Required on every request for a multi-workspace key.300  # Omit request_options for a single-workspace key.301  message = client.messages.create(302    model: Anthropic::Model::CLAUDE_OPUS_5,303    max_tokens: 1024,304    messages: [{role: "user", content: "Hello, Claude"}],305    request_options: {extra_headers: {"anthropic-workspace-id" => "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"}}306  )307308  puts message.content309  ```310</CodeGroup>311312If a request made with a key that isn't scoped to a workspace omits the header, the API returns a 400 `invalid_request_error`:313314```json JSON315{316  "type": "error",317  "error": {318    "type": "invalid_request_error",319    "message": "anthropic-workspace-id is required when authenticating with an identity-linked API key; send the id of the workspace this request acts in."320  },321  "request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"322}323```324325A header value that isn't a valid workspace ID returns a 400 `invalid_request_error` with the message `anthropic-workspace-id header must be a valid workspace ID.` If the workspace doesn't exist, or the key's user or service account doesn't have access to it, the API returns a 404 `not_found_error` with the message ``Workspace `<id>` not found.``, the same response as for any unknown workspace.326327Workload Identity Federation selects a workspace at token exchange instead; see the [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference) for details.328329### Key expiration330331When you create an API key from the [API keys page](https://platform.claude.com/settings/keys) in the Claude Console, you choose an expiration: a preset (3 hours, 1 day, 7 days, or 30 days), a custom duration, or **Never** for keys you store in a secrets manager and rotate yourself. If your organization has a maximum expiration policy, the Console limits presets and custom durations to the policy maximum, and **Never** is unavailable. Existing keys keep their current behavior; expiration is set at creation time and cannot be changed afterward. The same expiration choice applies when you [create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) in the Claude Console.332333Anthropic emails the key's creator as the expiration approaches: 7 days before expiration for keys created with a lifetime of at least 14 days, and 1 day before for keys with a lifetime of at least 7 days. Keys with shorter lifetimes expire without a warning email.334335After a key expires, requests made with it return a `401 authentication_error`. Create a new key to restore access; expired keys cannot be reactivated.336337The Console API keys table shows each key's expiration, and the Admin API reports each key's `expires_at` timestamp on the [List API Keys](https://platform.claude.com/docs/en/api/admin/api_keys/list) and [Retrieve API Key](https://platform.claude.com/docs/en/api/admin/api_keys/retrieve) endpoints, so you can audit and rotate keys before they expire. The field is `null` for keys without an expiration.338339Expiration limits the lifetime of a leaked credential, but it is not a substitute for secret hygiene. Regardless of expiration, store keys in a secrets manager and disable or delete any key you suspect has leaked.340341### Replacing workspace API keys342343If you have a workspace key, you may want to replace it with [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/wif-reference) or a personal or service account key. This provides better security and observability.344345See [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/wif-reference) for details on configuring Workload Identity Federation, which is preferred over long-lived keys.346347To replace a workspace key with a personal or service account key:3483491. **Decide the key type.** Your own tooling should use a personal key. A shared or unattended workload should use a service account key.3502. **Create a service account** if necessary. You may have to ask an organization admin to create one in [Settings → Service accounts](https://platform.claude.com/settings/service-accounts) and add it to the relevant workspace.3513. **Create the new key.** Create it specifically for the integration's workspace unless multiple workspaces are needed.3524. **Deploy the new key.** Replace the old key wherever the integration reads it, typically the `ANTHROPIC_API_KEY` environment variable or a secrets manager entry. For a multi-workspace key, also send the `anthropic-workspace-id` header as shown in [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace).3535. **Delete the old key.** Confirm that requests succeed, then delete the workspace key on the [API keys page](https://platform.claude.com/settings/keys).354355## Workload Identity Federation356357Workload Identity Federation (WIF) lets a workload authenticate with a short-lived identity token issued by an identity provider (IdP) you already trust, such as AWS IAM, Google Cloud, or any standards-compliant OIDC issuer (such as GitHub Actions, Kubernetes service accounts, SPIFFE, Microsoft Entra ID, or Okta). The workload exchanges its IdP-issued JWT at `POST /v1/oauth/token` for a short-lived Claude API access token, and the SDK refreshes that token automatically before it expires. There is no `sk-ant-api...` string to mint, distribute, or rotate.358359Federation removes long-lived Claude API keys from your environment, which shrinks the blast radius of a leaked credential and lets you manage access with the same IdP controls you already use for cloud resources. It does not, on its own, guarantee end-to-end security: the trust chain is only as strong as your identity provider's configuration, and a long-lived secret one hop upstream (for example, a static cloud credential that can mint IdP tokens) can still undermine it. Pair federation with your provider's controls, such as IP allowlists, MFA, and audit logging.360361To configure federation, you create three resources in the Claude Console (a service account, a federation issuer, and a federation rule) and then point your SDK at the rule. See [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) for the full setup walkthrough.362363## App Attest364365App Attest authenticates iOS and macOS apps that call the Claude API directly from the device. Each installation proves that it is a genuine, unmodified build of an app you registered in the Claude Console, using Apple's App Attest service. Anthropic then issues the device a short-lived access token that bills usage to your workspace. Tokens are scoped to your workspace, expire after one hour, and authorize only [Messages API](https://platform.claude.com/docs/en/api/messages/create) calls.366367To register your app and get a client ID, see [App Attest for iOS and macOS apps](https://platform.claude.com/docs/en/manage-claude/app-attest).368369## Next steps370371<CardGroup cols={2}>372  <Card title="Set up Workload Identity Federation" icon="lock" href="https://platform.claude.com/docs/en/manage-claude/workload-identity-federation">373    Configure issuers, rules, and service accounts, then exchange tokens374  </Card>375376  <Card title="Identity provider guides" icon="cloud" href="https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#identity-providers">377    Step-by-step guides for AWS, Google Cloud, Azure, GitHub Actions, Kubernetes, SPIFFE, and Okta378  </Card>379380  <Card title="WIF reference" icon="book" href="https://platform.claude.com/docs/en/manage-claude/wif-reference">381    Environment variables, validation rules, profile configuration, and error reference382  </Card>383384  <Card title="App Attest for iOS and macOS apps" icon="fingerprint" href="https://platform.claude.com/docs/en/manage-claude/app-attest">385    Let genuine installations of your app call the Claude API without shipping an API key386  </Card>387388  <Card title="Client SDKs" icon="code" href="https://platform.claude.com/docs/en/cli-sdks-libraries/overview">389    Python, TypeScript, C#, Go, Java, PHP, Ruby, and the CLI390  </Card>391</CardGroup>392
Files main
Menu

Theme