credential-for-each-customer changedmanage-claude/oauth-apps/linked-billing/credential-for-each-customer
Nearest release: v2.1.332, published under an hour before this site recorded the change. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.
## Before you begin ## Keep the OAuth tokens secret ## Call Claude with a customer’s access token ## Refresh the OAuth tokens ## Run an agent in a sandbox ## Check the result ## Decide whether to turn off operator-only authentication ## Implementation details, rules, and special cases ### If a refresh fails ### Full refresh sample ### If an API key can reach the process ### When you write each new access token to a sandbox ### For agents ## Next steps
The whole hunk
2285 lines, new pageA whole new page. There's nothing to diff it against, so here is what it says.
---
title: Use a separate credential for each customer
url: https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/credential-for-each-customer
description: Call Claude with each customer's own OAuth access token, so that code you don't fully control can bill only that customer.
---
<Warning>
Claude Platform OAuth is a Beta Service: prerelease software provided under your agreement with Anthropic, such as the [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms), and the [Service Specific Terms](https://www.anthropic.com/legal/service-specific-terms). Endpoints, parameters, and behavior can change during the beta. It might not be suitable for production use.
</Warning>
Each customer you link with [Linked billing](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing) comes with their own credential: an OAuth access token that can bill only that customer. Use it when code that you don’t fully control calls Claude for one customer, for example in an agent’s sandbox or a single-tenant deployment. A bug or a leak in that code can then bill only that customer.
If every request that bills a customer comes from your own back end, you don’t need these credentials. [Bill customers as your operator service account](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request), and skip this page.
## Before you begin
* **The customer’s OAuth tokens and connection ID:** The code exchange returned them when you [linked the customer](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#save-the-connection-and-its-tokens). A connection is the record that ties the customer’s Claude organization to one of your [user profiles](https://platform.claude.com/docs/en/manage-claude/user-profiles).
* **A refresh token:** [**Offline access**](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens) is on for your app, and the customer approved `billing:attribution offline_access`. A customer who approved without `offline_access` gets a refresh token by [approving again](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again), which replaces their connection without an unlink.
* **For the refresh samples:** A client assertion: a JWT from your identity provider for your app’s **Expected audience**, set up as your app’s [client authentication](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication). The samples read it from the file that the `CLIENT_ASSERTION_FILE` environment variable names or from the `CLIENT_ASSERTION` shell variable.
## Keep the OAuth tokens secret
Store each customer’s access token, refresh token, and their expiry times in a secret store that only the refreshing service can read. Anyone who holds an access token can bill that customer until the token expires. If a token leaks, [unlink the customer](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/manage-customers#unlink-a-customer) first, then link them again. If you lose a refresh token, [link the customer again](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).
## Call Claude with a customer’s access token
Send the customer’s access token in place of your operator service account’s credential:
* **In the Anthropic SDK:** Pass the customer’s access token as the client’s authentication token when you build the client.
* **In the `ant` CLI:** Set `ANTHROPIC_AUTH_TOKEN` to the token for the command.
* **In an HTTP request:** Send it as a bearer token in the `Authorization` header. Don’t send an `x-api-key` header.
<Warning>
Unset `ANTHROPIC_API_KEY` wherever you use a customer’s access token: some clients send the key instead, and Anthropic can bill you.
</Warning>
Those clients are the `ant` CLI and an SDK client that reads the token from `ANTHROPIC_AUTH_TOKEN`. For the reason and a guard against it, see [If an API key can reach the process](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-an-api-key-can-reach-the-process). If your lookup finds no token for the customer, stop before you build the client. Given a null token, the SDK might fall back to your own credential and bill you.
<CodeGroup>
```bash cURL
curl https://api.anthropic.com/v1/messages \
-H "authorization: Bearer $CUSTOMER_ACCESS_TOKEN" \
-H "anthropic-version: 2026-10-21" \
-H "content-type: application/json" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello, Claude"}]
}'
```
```bash CLI
ANTHROPIC_AUTH_TOKEN="$CUSTOMER_ACCESS_TOKEN" ant messages create \
--model claude-opus-5-5 \
--max-tokens 1024 \
--message '{role: user, content: "Hello, Claude"}'
```
```python Python
client = anthropic.Anthropic(auth_token=customer_access_token)
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
for block in message.content:
if block.type == "text":
print(block.text)
```
```typescript TypeScript
const client = new Anthropic({ authToken: customerAccessToken });
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }]
});
for (const block of message.content) {
if (block.type === "text") {
console.log(block.text);
}
}
```
```csharp C#
AnthropicClient client = new() { AuthToken = customerAccessToken };
var message = await client.Messages.Create(
new MessageCreateParams
{
Model = Model.ClaudeOpus5_5,
MaxTokens = 1024,
Messages = [new UserMessageParam { Content = "Hello, Claude" }],
}
);
foreach (var block in message.Content)
{
if (block.TryPickText(out var textBlock))
{
Console.WriteLine(textBlock.Text);
}
}
```
```go Go
client := anthropic.NewClient(option.WithAuthToken(customerAccessToken))
message, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5_5,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
},
})
if err != nil {
log.Fatal(err)
}
for _, block := range message.Content {
if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
fmt.Println(textBlock.Text)
}
}
```
```java Java
AnthropicClient client = AnthropicOkHttpClient.builder()
.authToken(customerAccessToken)
.build();
// ...
var params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_5_5)
.maxTokens(1024)
.addUserMessage("Hello, Claude")
.build();
var message = client.messages().create(params);
for (var block : message.content()) {
block.text().ifPresent(textBlock -> IO.println(textBlock.text()));
}
```
```php PHP
$client = new Client(authToken: $customerAccessToken);
$message = $client->messages->create(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Hello, Claude']],
model: Model::CLAUDE_OPUS_5_5,
);
foreach ($message->content as $block) {
if ($block instanceof \Anthropic\Messages\TextBlock) {
echo $block->text, PHP_EOL;
}
}
```
```ruby Ruby
client = Anthropic::Client.new(auth_token: customer_access_token)
message = client.messages.create(
model: Anthropic::Model::CLAUDE_OPUS_5_5,
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }]
)
message.content.each do |block|
puts(block.text) if block.is_a?(Anthropic::Models::TextBlock)
end
```
</CodeGroup>
A customer’s access token works on these endpoints only:
* `/v1/messages` and `/v1/chat/completions`
* `/v1/messages/count_tokens`
* the Models endpoints
On `/v1/messages` and `/v1/chat/completions`, the access token alone bills the customer. You don’t need the `anthropic-user-profile-id` header or [`billing_policy`](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request).
Send every other request and every request that you pay for as your operator service account. That includes requests that use billable code execution, which [can’t bill a customer](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing#if-you-use-code-execution).
Requests with the token run in the workspace that you set as your app’s default. Archiving it revokes every token in it: see [If you move to another workspace](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace). If a request with the token is refused, see [Linked billing errors](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/errors).
## Refresh the OAuth tokens
A customer’s access token lasts at most 1 hour. Before it expires, send the customer’s refresh token to the token endpoint for a new pair of tokens. Each refresh token works once, apart from a single repeat within 30 seconds to recover an answer that you lost.
<Warning>
A refresh token sent again more than 30 seconds after its first use ends the customer’s connection, and you have to link them again.
</Warning>
To make sure that you never send a used token late:
* Turn off automatic retries for the refresh request in your HTTP client and in any proxy.
* Refresh each customer’s OAuth tokens from one service, one refresh at a time for each customer. If the service has replicas, give them a shared lock. Hold it from reading a customer’s stored tokens until the new ones are stored.
* Store the new refresh token before you use the new access token.
The request is a `refresh_token` grant to `auth.claude.com`. It carries the refresh token and your app’s [client authentication](https://platform.claude.com/docs/en/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication): `client_id` and a client assertion. No SDK covers `auth.claude.com`, so the samples call it over HTTP. They show the plain call with no failure handling:
<CodeGroup exclude="shell:CLI">
```bash cURL
curl https://auth.claude.com/v1/oauth/token \
-H "content-type: application/json" \
-d @- <<JSON
{
"grant_type": "refresh_token",
"refresh_token": "$CUSTOMER_REFRESH_TOKEN",
"client_id": "clid_01ABcDeFgHiJkLmNoPqRsTuV",
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": "$CLIENT_ASSERTION"
}
JSON
```
<CodeGroupItem language="CLI">
The `ant` CLI has no command for `auth.claude.com`. Send the refresh with cURL or in your application’s language.
</CodeGroupItem>
```python Python
import os
from pathlib import Path
import httpx2 # comes with the Anthropic SDK
def refresh_tokens(refresh_token: str) -> dict:
assertion_file = Path(os.environ["CLIENT_ASSERTION_FILE"])
response = httpx2.post(
"https://auth.claude.com/v1/oauth/token",
json={
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": "clid_01ABcDeFgHiJkLmNoPqRsTuV",
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": assertion_file.read_text().strip(),
},
timeout=10,
)
if not response.is_success:
raise RuntimeError(f"Refresh failed: {response.status_code} {response.text}")
return response.json() # the new access_token and refresh_token
```
```typescript TypeScript
import { readFile } from "node:fs/promises";
async function refreshTokens(refreshToken: string) {
const jwt = await readFile(process.env.CLIENT_ASSERTION_FILE!, "utf8");
const response = await fetch("https://auth.claude.com/v1/oauth/token", {
method: "POST",
redirect: "error",
signal: AbortSignal.timeout(10_000),
headers: { "content-type": "application/json" },
body: JSON.stringify({
grant_type: "refresh_token",
refresh_token: refreshToken,
client_id: "clid_01ABcDeFgHiJkLmNoPqRsTuV",
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion: jwt.trim()
})
});
if (!response.ok) {
throw new Error(`Refresh failed: ${response.status} ${await response.text()}`);
}
return response.json(); // the new access_token and refresh_token
}
```
```csharp C#
using System.Net.Http.Json;
using System.Text.Json;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
async Task<JsonElement> RefreshTokens(string refreshToken)
{
var assertionFile = Environment.GetEnvironmentVariable("CLIENT_ASSERTION_FILE")!;
var jwt = await File.ReadAllTextAsync(assertionFile);
using var response = await http.PostAsJsonAsync(
"https://auth.claude.com/v1/oauth/token",
new Dictionary<string, string>
{
["grant_type"] = "refresh_token",
["refresh_token"] = refreshToken,
["client_id"] = "clid_01ABcDeFgHiJkLmNoPqRsTuV",
["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
["client_assertion"] = jwt.Trim(),
}
);
Cut at 300 lines. The page has the rest.
No line in this hunk matches that.