---
title: 고객마다 별도의 자격 증명 사용하기
url: https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer
description: 각 고객 자신의 OAuth 액세스 토큰으로 Claude를 호출하여, 완전히 제어하지 못하는 코드가 해당 고객에게만 요금을 청구할 수 있도록 합니다.
---

<Warning>
  Claude Platform OAuth는 Beta Service로, [상업 서비스 약관](https://www.anthropic.com/legal/commercial-terms) 및 [서비스별 약관](https://www.anthropic.com/legal/service-specific-terms) 등 Anthropic과 체결한 계약에 따라 제공되는 출시 전 소프트웨어입니다. 베타 기간 동안 엔드포인트, 매개변수 및 동작이 변경될 수 있습니다. 프로덕션 환경에서 사용하기에 적합하지 않을 수 있습니다.
</Warning>

[Linked billing](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing)으로 연결하는 각 고객에게는 고유한 자격 증명이 함께 제공됩니다. 이는 해당 고객에게만 요금을 청구할 수 있는 OAuth 액세스 토큰입니다. 완전히 제어하지 못하는 코드가 한 고객을 위해 Claude를 호출할 때(예: 에이전트의 샌드박스나 단일 테넌트 배포) 이 토큰을 사용하세요. 그러면 해당 코드의 버그나 유출이 발생해도 그 고객에게만 요금이 청구될 수 있습니다.

고객에게 요금을 청구하는 모든 요청이 자체 백엔드에서 발생한다면 이러한 자격 증명은 필요하지 않습니다. [운영자 서비스 계정으로 고객에게 요금을 청구](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request)하고 이 페이지는 건너뛰세요.

## 시작하기 전에

* **고객의 OAuth 토큰과 연결 ID:** [고객을 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#save-the-connection-and-its-tokens)했을 때 코드 교환에서 반환된 값입니다. 연결(connection)은 고객의 Claude 조직을 귀하의 [사용자 프로필](https://platform.claude.com/docs/ko/manage-claude/user-profiles) 중 하나에 묶는 레코드입니다.
* **리프레시 토큰:** 앱에 [**Offline access**](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens)가 켜져 있고, 고객이 `billing:attribution offline_access`를 승인한 상태여야 합니다. `offline_access` 없이 승인한 고객은 [다시 승인](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again)하여 리프레시 토큰을 받을 수 있으며, 이 경우 연결 해제 없이 기존 연결이 대체됩니다.
* **갱신 샘플의 경우:** 클라이언트 어설션이 필요합니다. 이는 앱의 **Expected audience**에 대해 ID 공급자가 발급한 JWT로, 앱의 [클라이언트 인증](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication)으로 설정되어 있어야 합니다. 샘플은 `CLIENT_ASSERTION_FILE` 환경 변수가 가리키는 파일이나 `CLIENT_ASSERTION` 셸 변수에서 이를 읽습니다.

## OAuth 토큰을 비밀로 유지하기

각 고객의 액세스 토큰, 리프레시 토큰 및 만료 시간을 갱신 서비스만 읽을 수 있는 시크릿 저장소에 보관하세요. 액세스 토큰을 가진 사람은 누구든 토큰이 만료될 때까지 해당 고객에게 요금을 청구할 수 있습니다. 토큰이 유출되면 먼저 [고객 연결을 해제](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#unlink-a-customer)한 다음 다시 연결하세요. 리프레시 토큰을 분실한 경우 [고객을 다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)하세요.

## 고객의 액세스 토큰으로 Claude 호출하기

운영자 서비스 계정의 자격 증명 대신 고객의 액세스 토큰을 보내세요.

* **Anthropic SDK에서:** 클라이언트를 생성할 때 고객의 액세스 토큰을 클라이언트의 인증 토큰으로 전달하세요.
* **`ant` CLI에서:** 명령에 대해 `ANTHROPIC_AUTH_TOKEN`을 해당 토큰으로 설정하세요.
* **HTTP 요청에서:** `Authorization` 헤더에 bearer 토큰으로 보내세요. `x-api-key` 헤더는 보내지 마세요.

<Warning>
  고객의 액세스 토큰을 사용하는 모든 곳에서 `ANTHROPIC_API_KEY`를 설정 해제하세요. 일부 클라이언트는 토큰 대신 키를 보내며, 이 경우 Anthropic이 귀하에게 요금을 청구할 수 있습니다.
</Warning>

그러한 클라이언트는 `ant` CLI와 `ANTHROPIC_AUTH_TOKEN`에서 토큰을 읽는 SDK 클라이언트입니다. 그 이유와 이를 방지하는 방법은 [API 키가 프로세스에 도달할 수 있는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-an-api-key-can-reach-the-process)를 참조하세요. 조회 결과 고객의 토큰을 찾지 못하면 클라이언트를 생성하기 전에 중단하세요. null 토큰이 주어지면 SDK가 귀하 자신의 자격 증명으로 대체하여 귀하에게 요금을 청구할 수 있습니다.

<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>

고객의 액세스 토큰은 다음 엔드포인트에서만 작동합니다.

* `/v1/messages` 및 `/v1/chat/completions`
* `/v1/messages/count_tokens`
* Models 엔드포인트

`/v1/messages`와 `/v1/chat/completions`에서는 액세스 토큰만으로 고객에게 요금이 청구됩니다. `anthropic-user-profile-id` 헤더나 [`billing_policy`](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request)는 필요하지 않습니다.

그 밖의 모든 요청과 귀하가 비용을 부담하는 모든 요청은 운영자 서비스 계정으로 보내세요. 여기에는 [고객에게 요금을 청구할 수 없는](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing#if-you-use-code-execution) 과금 대상 코드 실행을 사용하는 요청이 포함됩니다.

토큰을 사용한 요청은 앱의 기본값으로 설정한 워크스페이스에서 실행됩니다. 해당 워크스페이스를 보관하면 그 안의 모든 토큰이 취소됩니다. [다른 워크스페이스로 이동하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace)를 참조하세요. 토큰을 사용한 요청이 거부되면 [Linked billing 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/errors)를 참조하세요.

## OAuth 토큰 갱신하기

고객의 액세스 토큰은 최대 1시간 동안 유효합니다. 만료되기 전에 고객의 리프레시 토큰을 토큰 엔드포인트로 보내 새 토큰 쌍을 받으세요. 각 리프레시 토큰은 한 번만 작동하며, 예외적으로 잃어버린 응답을 복구하기 위해 30초 이내에 한 번 반복할 수 있습니다.

<Warning>
  처음 사용한 지 30초가 지난 후 리프레시 토큰을 다시 보내면 고객의 연결이 종료되며, 고객을 다시 연결해야 합니다.
</Warning>

사용된 토큰을 늦게 보내는 일이 없도록 하려면 다음을 따르세요.

* HTTP 클라이언트와 모든 프록시에서 갱신 요청에 대한 자동 재시도를 끄세요.
* 각 고객의 OAuth 토큰은 하나의 서비스에서, 고객마다 한 번에 하나의 갱신만 수행하세요. 서비스에 복제본이 있다면 공유 잠금을 사용하세요. 고객의 저장된 토큰을 읽을 때부터 새 토큰이 저장될 때까지 잠금을 유지하세요.
* 새 액세스 토큰을 사용하기 전에 새 리프레시 토큰을 저장하세요.

요청은 `auth.claude.com`에 대한 `refresh_token` 그랜트입니다. 이 요청에는 리프레시 토큰과 앱의 [클라이언트 인증](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication)인 `client_id` 및 클라이언트 어설션이 포함됩니다. `auth.claude.com`을 지원하는 SDK가 없으므로 샘플은 HTTP로 호출합니다. 샘플은 실패 처리가 없는 단순 호출을 보여줍니다.

<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">
    `ant` CLI에는 `auth.claude.com`용 명령이 없습니다. cURL이나 애플리케이션의 언어로 갱신 요청을 보내세요.
  </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(),
          }
      );
      if (!response.IsSuccessStatusCode)
      {
          var details = await response.Content.ReadAsStringAsync();
          throw new HttpRequestException($"Refresh failed: {(int)response.StatusCode} {details}");
      }

      // 새 access_token 및 refresh_token
      return await response.Content.ReadFromJsonAsync<JsonElement>();
  }
  ```

  ```go Go
  import (
  	"bytes"
  	"encoding/json"
  	"fmt"
  	"io"
  	"net/http"
  	"os"
  	"strings"
  	"time"
  )

  var httpClient = &http.Client{Timeout: 10 * time.Second}

  func refreshTokens(refreshToken string) (map[string]any, error) {
  	jwt, err := os.ReadFile(os.Getenv("CLIENT_ASSERTION_FILE"))
  	if err != nil {
  		return nil, err
  	}

  	body, err := json.Marshal(map[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":      strings.TrimSpace(string(jwt)),
  	})
  	if err != nil {
  		return nil, err
  	}

  	endpoint := "https://auth.claude.com/v1/oauth/token"
  	response, err := httpClient.Post(endpoint, "application/json", bytes.NewReader(body))
  	if err != nil {
  		return nil, err
  	}
  	defer response.Body.Close()
  	if response.StatusCode/100 != 2 {
  		details, _ := io.ReadAll(response.Body)
  		return nil, fmt.Errorf("refresh failed: %d %s", response.StatusCode, details)
  	}

  	var tokens map[string]any // the new access_token and refresh_token
  	err = json.NewDecoder(response.Body).Decode(&tokens)
  	return tokens, err
  }
  ```

  ```java Java
  import module java.base;
  import module java.net.http;
  import com.fasterxml.jackson.databind.JsonNode;
  import com.fasterxml.jackson.databind.ObjectMapper; // Jackson comes with the Anthropic SDK

  final HttpClient http = HttpClient.newHttpClient();
  final ObjectMapper mapper = new ObjectMapper();

  JsonNode refreshTokens(String refreshToken) throws Exception {
      var jwt = Files.readString(Path.of(System.getenv("CLIENT_ASSERTION_FILE")));

      var body = mapper.createObjectNode()
          .put("grant_type", "refresh_token")
          .put("refresh_token", refreshToken)
          .put("client_id", "clid_01ABcDeFgHiJkLmNoPqRsTuV")
          .put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
          .put("client_assertion", jwt.strip());

      var request = HttpRequest.newBuilder(URI.create("https://auth.claude.com/v1/oauth/token"))
          .header("content-type", "application/json")
          .timeout(Duration.ofSeconds(10))
          .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
          .build();
      var response = http.send(request, HttpResponse.BodyHandlers.ofString());
      if (response.statusCode() / 100 != 2) {
          throw new IOException("Refresh failed: " + response.statusCode() + " " + response.body());
      }
      return mapper.readTree(response.body()); // the new access_token and refresh_token
  }
  ```

  ```php PHP
  function refreshTokens(string $refreshToken): mixed
  {
      $jwt = file_get_contents((string) getenv('CLIENT_ASSERTION_FILE'))
          ?: throw new \RuntimeException('Cannot read the client assertion file');

      $body = json_encode([
          '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' => trim($jwt),
      ], JSON_THROW_ON_ERROR);

      $context = stream_context_create(['http' => [
          'method' => 'POST',
          'header' => 'content-type: application/json',
          'content' => $body,
          'timeout' => 10,
          'ignore_errors' => true, // keep the body of an error response
      ]]);
      $response = file_get_contents('https://auth.claude.com/v1/oauth/token', context: $context);
      $status = http_get_last_response_headers()[0] ?? '';
      if ($response === false || !preg_match('{^HTTP/\S+ 2}', $status)) {
          throw new \RuntimeException("Refresh failed: {$status} {$response}");
      }

      // 새 access_token 및 refresh_token
      return json_decode($response, associative: true, flags: JSON_THROW_ON_ERROR);
  }
  ```

  ```ruby Ruby
  require "json"
  require "net/http"

  def refresh_tokens(refresh_token)
    jwt = File.read(ENV.fetch("CLIENT_ASSERTION_FILE"))

    body = {
      grant_type: "refresh_token",
      refresh_token:,
      client_id: "clid_01ABcDeFgHiJkLmNoPqRsTuV",
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: jwt.strip
    }
    response = Net::HTTP.start("auth.claude.com", 443, use_ssl: true, read_timeout: 10) do |http|
      http.post("/v1/oauth/token", body.to_json, "content-type" => "application/json")
    end
    unless response.is_a?(Net::HTTPSuccess)
      raise "Refresh failed: #{response.code} #{response.body}"
    end

    JSON.parse(response.body) # the new access_token and refresh_token
  end
  ```
</CodeGroup>

응답에는 새 액세스 토큰과 새 리프레시 토큰이 포함됩니다. `expires_in`과 `refresh_token_expires_in`은 각각의 유효 기간을 초 단위로 제공합니다. 새 리프레시 토큰은 보낸 토큰을 대체하며, 이전 액세스 토큰은 몇 분 이내에 작동을 멈춥니다.

갱신이 실패한 후 토큰을 다시 보내기 전에 [갱신이 실패한 경우 해야 할 일](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails)을 읽으세요. 일부 재시도는 연결을 종료시키며, 일부 실패는 모든 고객의 갱신을 일시 중지해야 함을 의미합니다. [전체 갱신 샘플](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#full-refresh-sample)이 이러한 실패를 처리합니다.

리프레시 토큰은 코드 교환 시점부터 최대 1년 동안 유효하며, 갱신해도 이 기간은 연장되지 않습니다. 만료되기 전에 [고객을 다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)하세요.

## 샌드박스에서 에이전트 실행하기

이 섹션을 사용하기 전에 [Linked Billing 베타 약관](https://www.anthropic.com/legal/linked-billing-terms)의 4.1(b)항을 읽으세요. 이에 대해 질문이 있으면 Anthropic 계정 팀에 문의하세요.

에이전트가 샌드박스에서 한 고객을 위해 작동할 때는 다음 규칙을 따르세요.

* 샌드박스에는 액세스 토큰만 제공하고, 리프레시 토큰은 절대 제공하지 마세요. 백엔드가 토큰을 갱신하고 각 새 액세스 토큰을 샌드박스로 보냅니다.
* 샌드박스가 어떤 고객을 위해 작동하는지는 파드 ID와 같은 샌드박스 자체의 ID로 결정하세요. 샌드박스가 보내는 값으로는 절대 결정하지 마세요.
* 샌드박스에는 해당 샌드박스가 담당하는 고객의 토큰만 보내세요.
* 샌드박스에 마운트된 ID 토큰이나 클라우드 메타데이터 서버에 대한 액세스를 제공하지 마세요.

마지막 규칙은 샌드박스가 앱의 클라이언트 인증이나 귀하의 [페더레이션 규칙](https://platform.claude.com/docs/ko/manage-claude/workload-identity-federation) 중 하나와 일치하는 JWT를 얻지 못하도록 합니다. 그러한 JWT가 있으면 샌드박스 안의 코드가 앱이나 서비스 계정 중 하나로 인증할 수 있습니다.

Anthropic SDK, Claude Code 및 [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview)는 구성 프로필의 자격 증명 파일에서 액세스 토큰을 읽을 수 있습니다. 파일 형식은 [프로필 구성 파일](https://platform.claude.com/docs/ko/manage-claude/wif-reference#profile-configuration-file)을 참조하세요. 샌드박스를 설정하려면 다음을 따르세요.

<Steps>
  <Step title="프로필 추가하기">
    샌드박스에서 구성 디렉터리를 만드세요. 그 안에 인증 유형이 `user_oauth`인 프로필을 `configs/customer.json`에 추가하세요. 프로필에 `client_id`를 지정하지 마세요. 지정하면 SDK는 파일에 리프레시 토큰이 있을 것으로 예상하고 토큰을 직접 갱신합니다.

    <File filename="configs/customer.json">
      ```json
      {
        "version": "1.0",
        "authentication": {
          "type": "user_oauth"
        }
      }
      ```
    </File>
  </Step>

  <Step title="액세스 토큰 쓰기">
    에이전트가 시작되기 전에 같은 구성 디렉터리의 `credentials/customer.json`에 액세스 토큰을 써서 `configs`와 `credentials`가 나란히 위치하도록 하세요. 각 갱신 직후에 다시 쓰세요. `expires_at`은 Unix 초 단위의 토큰 만료 시간입니다. 안전하게 쓰는 코드는 [각 새 액세스 토큰을 샌드박스에 쓸 때](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#when-you-write-each-new-token-to-a-sandbox)를 참조하세요.

    ```json credentials/customer.json
    {
      "type": "oauth_token",
      "access_token": "sk-ant-oat01-...",
      "expires_at": 1793635200
    }
    ```
  </Step>

  <Step title="클라이언트가 프로필을 가리키도록 설정하기">
    `ANTHROPIC_CONFIG_DIR`을 구성 디렉터리로, `ANTHROPIC_PROFILE`을 `customer`로 설정하세요.
  </Step>

  <Step title="그 밖의 모든 자격 증명 제거하기">
    샌드박스의 다른 모든 자격 증명은 각각 프로필보다 우선할 수 있으므로 모두 설정 해제하세요. 여기에는 다음이 포함됩니다.

    * `ANTHROPIC_API_KEY` 및 `ANTHROPIC_AUTH_TOKEN` 환경 변수
    * Claude Code의 `CLAUDE_CODE_OAUTH_TOKEN` 환경 변수와 `apiKeyHelper` 설정
  </Step>
</Steps>

SDK는 재시작 없이 각 새 토큰을 인식합니다. [각 새 액세스 토큰을 샌드박스에 쓸 때](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#when-you-write-each-new-token-to-a-sandbox)를 참조하세요.

## 결과 확인하기

요청이 고객에게 청구되었는지 확인하려면 [청구된 요청이 표시되는 위치](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#check-the-result)를 참조하세요. 토큰이 해당 고객으로 제한되는지 확인하려면 다음을 확인하세요.

* 토큰을 사용한 요청에서 다른 사용자 프로필을 지정하면 `400 invalid_request_error`를 받습니다.
* 갱신 후 몇 분이 지나면, 이전 액세스 토큰을 사용한 요청은 `401 authentication_error`를 받습니다.

## 운영자 전용 인증을 끌지 결정하기

기본적으로 운영자 서비스 계정은 고객의 액세스 토큰 없이도 연결된 모든 고객에게 요금을 청구할 수 있습니다. 고객의 사용자 프로필을 지정하고 [`billing_policy`](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request)에서 `bill_to: "user_profile"`을 설정하면 됩니다. 이 기본값을 “operator-only authentication”(운영자 전용 인증)이라고 하며, 고객의 액세스 토큰이 만료된 후에도 계속 작동합니다.

모든 고객의 요청이 각자의 액세스 토큰을 사용하게 되면 운영자 전용 인증을 끌 수 있습니다. 그러면 고객 자신의 액세스 토큰만 해당 고객에게 요금을 청구할 수 있으므로, 잘못된 사용자 프로필을 지정하는 버그가 있어도 잘못된 고객에게 요금이 청구될 수 없습니다.

이 경우 모든 고객의 요청이 갱신에 의존하게 됩니다. 고객의 리프레시 토큰을 분실하면 고객이 [다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)할 때까지 요금을 청구할 수 없습니다. **Offline access**를 끄거나 [기본 워크스페이스](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#default-workspace)를 지우는 등 갱신을 중단시키는 모든 조치는 액세스 토큰이 만료됨에 따라 모든 고객의 요청을 실패하게 만듭니다.

Claude Console은 앱에 `billing:attribution`, `offline_access` 및 기본 워크스페이스가 있는지만 확인합니다. 운영자 전용 인증을 끄기 전에 다음 사항을 직접 확인하세요.

* 저장소에 연결된 모든 고객의 리프레시 토큰이 보관되어 있습니다.
* 고객의 액세스 토큰을 사용한 요청이 작동합니다.

운영자 전용 인증을 끄려면 다음을 따르세요.

1. Console에서 앱의 **Client authentication** 탭을 여세요.
2. 운영자 서비스 계정 아래에서 **Disable operator-only tokenless authentication**을 켜고 대화 상자에서 확인하세요. API에서의 이름은 `disable_operator_only_auth`입니다.

그러면 다음 규칙이 적용됩니다.

* 연결된 고객에 대해 `bill_to: "user_profile"`을 설정하고 서비스 계정만으로 보낸 요청은 `403 user_profile_not_billable`을 받습니다. 고객은 여전히 **Linked**로 표시되므로 로그에서 이 오류를 주시하세요.
* 서비스 계정은 여전히 사용자 프로필을 관리하고 귀하가 비용을 부담하는 요청을 보낼 수 있습니다.
* 기본값으로 되돌리려면 같은 설정을 끄세요.

## 구현 세부 사항, 규칙 및 특수한 경우

이 페이지의 나머지 부분은 단계에 대한 세부 사항입니다. 실패한 갱신, 전체 갱신 샘플, 그리고 API 키나 갱신이 실행 중인 클라이언트에 미치는 영향을 다룹니다. 지원 중단된 스코프만 승인한 고객에게는 자체 액세스 토큰이 없습니다. [지원 중단된 스코프를 여전히 사용하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-still-use-the-deprecated-scope)를 참조하세요.

### 갱신이 실패한 경우

갱신은 보낸 리프레시 토큰을 대체합니다. 대체된 토큰이 다시 도착했을 때 어떤 일이 일어나는지는 도착 시점에 따라 다릅니다.

* **30초 이내, 처음인 경우:** 새 토큰 쌍을 반환하고 받지 못한 쌍을 취소합니다. 이를 통해 응답을 잃어버린 갱신을 반복할 수 있습니다.
* **30초 이내, 처음이지만, 보낸 토큰이 대체될 때 생성된 지 30초 미만이었던 경우:** `invalid_grant`를 받으며, 연결은 유지됩니다.
* **30초 이내, 그 이후의 모든 경우:** `invalid_grant`를 받으며, 연결은 유지됩니다.
* **30초 이후:** `invalid_grant`를 받고 연결이 종료됩니다. 모든 토큰이 취소되고, 고객은 **Unlinked**로 표시되며, 고객이 다시 연결할 때까지 어떤 것도 고객에게 요금을 청구할 수 없습니다.

갱신이 실패한 후 해야 할 일은 리프레시 토큰이 `auth.claude.com`에 도달하여 사용되었는지에 따라 다릅니다.

| 갱신이 받은 결과 | 의미 | 해야 할 일 |
| ----- | ----- | ----- |
| 연결 시간 초과를 포함하여 요청이 `auth.claude.com`에 도달하지 못함 | 토큰이 전송되지 않았음 | 나중에 다시 보내기 |
| `429` | 아무것도 취소되지 않았음 | 기다린 후 다시 보내기 |
| `503` 거부: `retry-after` 헤더와 본문 최상위 수준의 `"type": "error"` | 아무것도 취소되지 않았음 | 기다린 후 다시 보내기 |
| `invalid_grant`를 제외한 그 밖의 모든 `4xx` | 아무것도 취소되지 않았음 | 원인을 해결한 후 다시 보내기 |
| 그 밖의 모든 `5xx` 또는 요청이 나간 후 네트워크 끊김 | 작동했을 수 있음 | 즉시 한 번 더 보내기 |
| 제시간에 응답 없음(읽기 시간 초과) | 아직 실행 중일 수 있음 | 다시 보내지 않기 |
| `invalid_grant` | 지금은 토큰을 사용할 수 없음 | 보내기 중단 |

**기다린 후 다시 보내기:** 최소한 `retry-after`가 지정한 시간만큼 기다리세요. `429`에 `retry-after` 헤더가 없으면 다시 보내기 전에 백오프하세요. 두 표시 중 하나라도 없는 `503`은 그 밖의 `5xx`로 간주됩니다.

**원인을 해결한 후 다시 보내기:**

* `unauthorized_client`: `error_description`에 보통 원인이 명시됩니다. 예를 들어 기본 워크스페이스가 없거나 앱에서 `offline_access`가 더 이상 켜져 있지 않은 경우입니다.
* `invalid_client`: 클라이언트 어설션이 실패했습니다. [클라이언트 어설션 클레임](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/endpoints-and-parameters#client-assertion-claims)과 대조하여 확인하세요.
* `invalid_scope`: 요청에 `scope` 매개변수를 보냈거나, 앱에 더 이상 `billing:attribution`이 없습니다.
* `invalid_request`와 같은 그 밖의 모든 `4xx`: 요청을 수정하세요.

운영자 서비스 계정을 변경하거나 보관한 경우, 유효한 토큰의 모든 갱신은 `unauthorized_client`를 받으며 다시 보내도 도움이 되지 않습니다. [서비스 계정을 변경하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-change-the-service-account)를 참조하세요.

**즉시 한 번 더 보내기:** `auth.claude.com`은 토큰을 대체한 후 30초 이내에 두 번째 요청을 받아야 합니다. 대체 시점은 알 수 없으므로 첫 번째 요청을 보낸 시점부터 계산하고, 두 번째 요청이 도착할 시간을 남겨 두세요. 그런 다음:

* 두 번째 요청이 새 토큰을 반환하면, 이를 저장하고 새 토큰만 사용하세요.
* 그 밖의 결과를 반환하거나, 응답이 없거나, 제시간에 보낼 수 없으면 토큰을 다시 보내지 마세요.

**다시 보내지 않기:** 읽기 시간 초과나 복구할 수 없는 응답 손실 이후에는 해당 고객의 갱신을 중단하고 [고객을 다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)하세요.

**보내기 중단:** 해당 고객의 갱신을 중단하세요. `invalid_grant`는 보통 다음 중 하나를 의미하며, 응답에는 어느 것인지 나와 있지 않으므로 누군가를 다시 연결하기 전에 처음 두 가지를 확인하세요.

* 고객의 조직이 정지되었습니다. 고객 연결을 해제하지 말고 리프레시 토큰을 보관하세요. 정지가 해제되면 다시 작동합니다. 확인하려면 [Anthropic 지원팀](https://support.claude.com/en/articles/9015913-how-to-get-support) 또는 Anthropic 계정 팀(있는 경우)에 문의하세요.
* 모든 고객의 갱신이 동시에 `invalid_grant`를 받았습니다. [보관된 워크스페이스](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace)와 같이 귀하 측의 원인을 찾아보세요.
* 토큰이 만료되었거나 이미 사용되었거나, 연결이 종료되었거나, 해당 워크스페이스가 보관되었습니다. [고객을 다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)하세요.

네트워크 연결 끊김, `5xx` 응답 또는 시간 초과는 `auth.claude.com`에 장애가 있음을 의미할 수 있습니다. 이로 인해 한 고객의 갱신을 중단했다면, 장애로 더 많은 연결을 잃지 않도록 다음을 따르세요.

1. 다른 고객의 갱신을 일시 중지하세요.
2. 한 고객을 갱신하세요.
3. 그 갱신이 성공하거나 `4xx` 응답을 받은 후에만 나머지를 재개하세요.

### 전체 갱신 샘플

이 버전의 갱신은 [갱신이 실패한 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails)를 따릅니다. 단순 호출에 다음과 같은 안전장치를 추가합니다.

* 액세스 토큰의 남은 시간이 10분 미만일 때 갱신합니다.
* 저장된 토큰을 읽을 때부터 새 토큰이 저장될 때까지 고객별 잠금을 유지합니다.
* 리프레시 토큰이 프로세스를 떠나기 전에 저장된 토큰을 `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`)로 표시하여, 충돌이 발생해도 두 번째 전송으로 이어지지 않도록 합니다.
* `auth.claude.com`에 도달하기까지 최대 2초, 응답을 받기까지 최대 10초를 기다립니다.
* 첫 번째 요청 후 4초 이내에만 두 번째 요청을 보냅니다. 이렇게 하면 두 번째 요청이 30초 이내에 도착할 시간이 남습니다. 또한 두 번째 요청을 10초 대기 시간 안에 유지하여, 시간 초과된 요청이 다시 전송되는 일이 없도록 합니다.
* 시크릿 저장소에 대한 쓰기만 실패한 경우, 쓰기를 다시 시도하며 다시 갱신하지 않습니다.

샘플은 다음 세 가지를 귀하에게 맡깁니다.

* 모든 복제본이 공유하는 잠금(샘플 자체의 잠금은 다른 복제본에 미치지 않기 때문)
* `429` 또는 `503` 거부 후 기다렸다가 다시 보내기(샘플은 이를 오류로 보고함)
* 갱신 손실 후 모든 복제본에서 다른 고객의 갱신을 일시 중지하기

각 고객에 대해 갱신 함수를 10분보다 짧은 간격으로 호출하여, 항상 그 여유 시간 안에서 실행되도록 하세요.

`refresh_connection()` (typescript, go, java, php: `refreshConnection()`; csharp: `Connections.RefreshConnection()`)는 리프레시 토큰을 다시 보내면 안 될 때 `RefreshOnHoldError` (csharp, java, php: `RefreshOnHoldException`)로 실패합니다. 또한 해당 고객에 대한 이후의 모든 호출에서도 실패합니다. 저장된 레코드는 `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`)와 `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`)를 유지하므로, 나중에 보류가 설정된 이유를 알 수 있습니다. 쓰기만 실패한 경우, 오류의 `new_tokens` (typescript, java, php: `newTokens`; csharp, go: `NewTokens`)에 저장할 토큰이 담겨 있습니다.

다음 설정은 공유 이름을 정의합니다. `load_tokens()` (typescript, go, java, php: `loadTokens()`; csharp: `LoadTokens()`)와 `save_tokens()` (typescript, go, java, php: `saveTokens()`; csharp: `SaveTokens()`)는 자체 시크릿 저장소에 맞게 직접 작성하세요.

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    이 설정은 뒤따르는 갱신 함수와 함께 사용되며, 해당 함수는 단일 셸 명령보다 더 많은 로직이 필요합니다. 둘 다 애플리케이션의 언어로 작성하세요.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    이 설정은 뒤따르는 갱신 함수와 함께 사용되며, 해당 함수는 단일 셸 명령보다 더 많은 로직이 필요합니다. 둘 다 애플리케이션의 언어로 작성하세요.
  </CodeGroupItem>

  ```python Python
  import os
  import threading
  import time
  from collections import defaultdict
  from dataclasses import dataclass, field, replace
  from pathlib import Path

  import httpx2  # comes with the Anthropic SDK

  TOKEN_URL = "https://auth.claude.com/v1/oauth/token"
  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"
  JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
  REFRESH_MARGIN_SECONDS = 600
  REQUEST_TIMEOUT = httpx2.Timeout(10, connect=2)
  SECOND_REQUEST_DEADLINE_SECONDS = 4  # keep this under the 10-second read timeout


  @dataclass
  class ConnectionTokens:
      refresh_token: str = field(repr=False)
      access_token: str = field(repr=False)
      expires_at: int  # Unix seconds
      refresh_expires_at: int  # Unix seconds
      on_hold: bool = False  # True: the refresh token might have been used
      hold_reason: str | None = None  # "lost" or "invalid_grant"


  class RefreshOnHoldError(Exception):
      """The refresh token must not be sent again. Don't catch this to try again.

      If new_tokens is set, only the write failed: store those tokens.
      """

      new_tokens: ConnectionTokens | None = None


  def client_assertion() -> str:
      """Reads the JWT that authenticates your app to auth.claude.com."""
      return Path(os.environ["CLIENT_ASSERTION_FILE"]).read_text().strip()


  def load_tokens(connection_id: str) -> ConnectionTokens:
      """Reads the connection's newest tokens from your secret store."""
      raise NotImplementedError("Read the tokens from your secret store.")


  def save_tokens(connection_id: str, tokens: ConnectionTokens) -> None:
      """Writes the connection's newest tokens to your secret store."""
      raise NotImplementedError("Write the tokens to your secret store.")
  ```

  ```typescript TypeScript
  import { readFile } from "node:fs/promises";
  import type { IncomingHttpHeaders } from "node:http";
  import { request } from "node:https";

  const TOKEN_URL = "https://auth.claude.com/v1/oauth/token";
  const CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
  const JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
  const REFRESH_MARGIN_SECONDS = 600;
  const SECOND_REQUEST_DEADLINE_MS = 4_000; // keep this under the 10-second timeout

  interface ConnectionTokens {
    refreshToken: string;
    accessToken: string;
    expiresAt: number; // Unix seconds
    refreshExpiresAt: number; // Unix seconds
    onHold?: boolean; // true: the refresh token might have been used
    holdReason?: "lost" | "invalid_grant";
  }

  /** The refresh token must not be sent again. Don't catch this to try again. */
  class RefreshOnHoldError extends Error {
    override name = "RefreshOnHoldError";
    readonly #newTokens?: ConnectionTokens; // private, so that printing the error doesn't show them

    constructor(message: string, newTokens?: ConnectionTokens) {
      super(message);
      this.#newTokens = newTokens;
    }

    /** If set, only the write failed: store these tokens. */
    get newTokens() {
      return this.#newTokens;
    }
  }

  /** Reads the JWT that authenticates your app to auth.claude.com. */
  async function clientAssertion(): Promise<string> {
    return (await readFile(process.env.CLIENT_ASSERTION_FILE!, "utf8")).trim();
  }

  /** Reads the connection's newest tokens from your secret store. */
  async function loadTokens(connectionId: string): Promise<ConnectionTokens> {
    throw new Error("Read the tokens from your secret store.");
  }

  /** Writes the connection's newest tokens to your secret store. */
  async function saveTokens(connectionId: string, tokens: ConnectionTokens): Promise<void> {
    throw new Error("Write the tokens to your secret store.");
  }
  ```

  ```csharp C#
  using System.Collections.Concurrent;
  using System.Diagnostics;
  using System.Text;
  using System.Text.Json;

  record ConnectionTokens(
      string RefreshToken,
      string AccessToken,
      long ExpiresAt, // Unix seconds
      long RefreshExpiresAt, // Unix seconds
      bool OnHold = false, // true: the refresh token might have been used
      string? HoldReason = null // "lost" or "invalid_grant"
  )
  {
      // 토큰이 로그에 남지 않도록 합니다.
      public override string ToString() =>
          $"ConnectionTokens {{ ExpiresAt = {ExpiresAt}, OnHold = {OnHold}, HoldReason = {HoldReason} }}";
  }

  /// <summary>리프레시 토큰을 다시 보내면 안 됩니다. 재시도하려고 이 예외를 catch하지 마세요.</summary>
  class RefreshOnHoldException(string message) : Exception(message)
  {
      /// <summary>설정된 경우 쓰기만 실패한 것입니다. 이 토큰을 저장하세요.</summary>
      public ConnectionTokens? NewTokens { get; init; }
  }

  static partial class Connections
  {
      const string TokenUrl = "https://auth.claude.com/v1/oauth/token";
      const string ClientId = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
      const string JwtBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
      const int RefreshMarginSeconds = 600;
      static readonly TimeSpan SecondRequestDeadline = TimeSpan.FromSeconds(4); // keep this under the 10-second timeout

      /// <summary>auth.claude.com에 앱을 인증하는 JWT를 읽습니다.</summary>
      static string ClientAssertion() =>
          File.ReadAllText(Environment.GetEnvironmentVariable("CLIENT_ASSERTION_FILE")!).Trim();

      /// <summary>시크릿 저장소에서 연결의 최신 토큰을 읽습니다.</summary>
      static Task<ConnectionTokens> LoadTokens(string connectionId) =>
          throw new NotImplementedException("Read the tokens from your secret store.");

      /// <summary>연결의 최신 토큰을 시크릿 저장소에 씁니다.</summary>
      static Task SaveTokens(string connectionId, ConnectionTokens tokens) =>
          throw new NotImplementedException("Write the tokens to your secret store.");
  }
  ```

  ```go Go
  import (
  	"bytes"
  	"encoding/json"
  	"errors"
  	"fmt"
  	"io"
  	"net"
  	"net/http"
  	"net/http/httptrace"
  	"os"
  	"strings"
  	"sync"
  	"time"
  )

  const (
  	tokenURL              = "https://auth.claude.com/v1/oauth/token"
  	clientID              = "clid_01ABcDeFgHiJkLmNoPqRsTuV"
  	jwtBearer             = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
  	refreshMargin         = 10 * time.Minute
  	secondRequestDeadline = 4 * time.Second // keep this under the 10-second timeout
  )

  var httpClient = &http.Client{
  	Timeout: 10 * time.Second,
  	Transport: &http.Transport{
  		Proxy:               http.ProxyFromEnvironment,
  		DialContext:         (&net.Dialer{Timeout: 2 * time.Second}).DialContext,
  		TLSHandshakeTimeout: 2 * time.Second,
  	},
  	CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
  }

  type ConnectionTokens struct {
  	RefreshToken     string
  	AccessToken      string
  	ExpiresAt        int64  // Unix seconds
  	RefreshExpiresAt int64  // Unix seconds
  	OnHold           bool   // true: the refresh token might have been used
  	HoldReason       string // "lost" or "invalid_grant"
  }

  // String은 토큰이 로그에 남지 않게 합니다.
  func (t ConnectionTokens) String() string {
  	return fmt.Sprintf("ConnectionTokens{ExpiresAt: %d, OnHold: %t, HoldReason: %q}", t.ExpiresAt, t.OnHold, t.HoldReason)
  }

  // RefreshOnHoldError는 리프레시 토큰을 다시 보내면 안 된다는 뜻입니다. 재시도하지 마세요.
  type RefreshOnHoldError struct {
  	Message   string
  	NewTokens *ConnectionTokens // if set, only the write failed: store these tokens
  }

  func (e *RefreshOnHoldError) Error() string { return e.Message }

  // clientAssertion은 앱을 auth.claude.com에 인증하는 JWT를 읽습니다.
  func clientAssertion() (string, error) {
  	jwt, err := os.ReadFile(os.Getenv("CLIENT_ASSERTION_FILE"))
  	return strings.TrimSpace(string(jwt)), err
  }

  // loadTokens는 시크릿 저장소에서 연결의 최신 토큰을 읽습니다.
  func loadTokens(connectionID string) (ConnectionTokens, error) {
  	return ConnectionTokens{}, errors.New("read the tokens from your secret store")
  }

  // saveTokens는 연결의 최신 토큰을 시크릿 저장소에 씁니다.
  func saveTokens(connectionID string, tokens ConnectionTokens) error {
  	return errors.New("write the tokens to your secret store")
  }
  ```

  ```java Java
  import module java.base;
  import module java.net.http;
  import com.fasterxml.jackson.databind.JsonNode;
  import com.fasterxml.jackson.databind.ObjectMapper; // Jackson comes with the Anthropic SDK

  static final URI TOKEN_URL = URI.create("https://auth.claude.com/v1/oauth/token");
  static final String CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
  static final String JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
  static final long REFRESH_MARGIN_SECONDS = 600;
  static final Duration SECOND_REQUEST_DEADLINE = Duration.ofSeconds(4); // keep this under the 10-second read timeout

  record ConnectionTokens(
      String refreshToken,
      String accessToken,
      long expiresAt, // Unix seconds
      long refreshExpiresAt, // Unix seconds
      boolean onHold, // true: the refresh token might have been used
      String holdReason // "lost" or "invalid_grant"
  ) {
      @Override // keeps the tokens out of logs
      public String toString() {
          return "ConnectionTokens[expiresAt=" + expiresAt + ", onHold=" + onHold + ", holdReason=" + holdReason + "]";
      }

      ConnectionTokens withHold(String reason) {
          return new ConnectionTokens(refreshToken, accessToken, expiresAt, refreshExpiresAt, true, reason);
      }
  }

  record AccessToken(String value, long expiresAt /* Unix seconds */) {
      @Override // keeps the token out of logs
      public String toString() {
          return "AccessToken[expiresAt=" + expiresAt + "]";
      }
  }

  /** The refresh token must not be sent again. Don't catch this to try again. */
  static class RefreshOnHoldException extends RuntimeException {
      /** If set, only the write failed: store these tokens. */
      ConnectionTokens newTokens;

      RefreshOnHoldException(String message) {
          super(message);
      }
  }

  /** Reads the JWT that authenticates your app to auth.claude.com. */
  String clientAssertion() throws IOException {
      return Files.readString(Path.of(System.getenv("CLIENT_ASSERTION_FILE"))).strip();
  }

  /** Reads the connection's newest tokens from your secret store. */
  ConnectionTokens loadTokens(String connectionId) throws IOException {
      throw new UnsupportedOperationException("Read the tokens from your secret store.");
  }

  /** Writes the connection's newest tokens to your secret store. */
  void saveTokens(String connectionId, ConnectionTokens tokens) throws IOException {
      throw new UnsupportedOperationException("Write the tokens to your secret store.");
  }
  ```

  ```php PHP
  const TOKEN_URL = 'https://auth.claude.com/v1/oauth/token';
  const CLIENT_ID = 'clid_01ABcDeFgHiJkLmNoPqRsTuV';
  const JWT_BEARER = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
  const REFRESH_MARGIN_SECONDS = 600;
  const SECOND_REQUEST_DEADLINE_SECONDS = 4; // keep this under the 10-second timeout

  final class ConnectionTokens
  {
      public function __construct(
          public readonly string $refreshToken,
          public readonly string $accessToken,
          public readonly int $expiresAt, // Unix seconds
          public readonly int $refreshExpiresAt, // Unix seconds
          public readonly bool $onHold = false, // true: the refresh token might have been used
          public readonly ?string $holdReason = null, // 'lost' or 'invalid_grant'
      ) {}

      /** Keeps the tokens out of var_dump and print_r. */
      public function __debugInfo(): array
      {
          return ['expiresAt' => $this->expiresAt, 'onHold' => $this->onHold, 'holdReason' => $this->holdReason];
      }

      public function withHold(string $reason): self
      {
          return new self(
              refreshToken: $this->refreshToken,
              accessToken: $this->accessToken,
              expiresAt: $this->expiresAt,
              refreshExpiresAt: $this->refreshExpiresAt,
              onHold: true,
              holdReason: $reason,
          );
      }
  }

  /** The refresh token must not be sent again. Don't catch this to try again. */
  final class RefreshOnHoldException extends \RuntimeException
  {
      /** If set, only the write failed: store these tokens. */
      public ?ConnectionTokens $newTokens = null;
  }

  /** Reads the JWT that authenticates your app to auth.claude.com. */
  function clientAssertion(): string
  {
      $jwt = file_get_contents((string) getenv('CLIENT_ASSERTION_FILE'))
          ?: throw new \RuntimeException('Cannot read the client assertion file');
      return trim($jwt);
  }

  /** Reads the connection's newest tokens from your secret store. */
  function loadTokens(string $connectionId): ConnectionTokens
  {
      throw new \LogicException('Read the tokens from your secret store.');
  }

  /** Writes the connection's newest tokens to your secret store. */
  function saveTokens(string $connectionId, ConnectionTokens $tokens): void
  {
      throw new \LogicException('Write the tokens to your secret store.');
  }
  ```

  ```ruby Ruby
  require "json"
  require "net/http"

  TOKEN_URL = URI("https://auth.claude.com/v1/oauth/token")
  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"
  JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
  REFRESH_MARGIN_SECONDS = 600
  SECOND_REQUEST_DEADLINE_SECONDS = 4 # keep this under the 10-second read timeout

  ConnectionTokens = Data.define(
    :refresh_token,
    :access_token,
    :expires_at, # Unix seconds
    :refresh_expires_at, # Unix seconds
    :on_hold, # true: the refresh token might have been used
    :hold_reason # "lost" or "invalid_grant"
  ) do
    def initialize(on_hold: false, hold_reason: nil, **) = super

    # 토큰이 로그에 남지 않도록 합니다.
    def inspect = "#<data ConnectionTokens expires_at=#{expires_at} on_hold=#{on_hold} hold_reason=#{hold_reason.inspect}>"
    alias_method :to_s, :inspect
  end

  # 리프레시 토큰을 다시 보내면 안 됩니다. 재시도하려고 이 예외를 rescue하지 마세요.
  # new_tokens가 설정되어 있으면 쓰기만 실패한 것이므로 해당 토큰을 저장하세요.
  class RefreshOnHoldError < StandardError
    attr_accessor :new_tokens
  end

  # auth.claude.com에 앱을 인증하는 JWT를 읽습니다.
  def client_assertion = File.read(ENV.fetch("CLIENT_ASSERTION_FILE")).strip

  # 시크릿 저장소에서 연결의 최신 토큰을 읽습니다.
  def load_tokens(connection_id)
    raise NotImplementedError, "Read the tokens from your secret store."
  end

  # 연결의 최신 토큰을 시크릿 저장소에 씁니다.
  def save_tokens(connection_id, tokens)
    raise NotImplementedError, "Write the tokens to your secret store."
  end
  ```
</CodeGroup>

다음 갱신 함수는 위 설정을 사용합니다.

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    이 갱신은 단일 셸 명령보다 더 많은 로직이 필요합니다. 애플리케이션의 언어로 작성하세요.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    이 갱신은 단일 셸 명령보다 더 많은 로직이 필요합니다. 애플리케이션의 언어로 작성하세요.
  </CodeGroupItem>

  ```python Python
  connection_locks: defaultdict[str, threading.Lock] = defaultdict(threading.Lock)


  def error_body(response: httpx2.Response) -> dict:
      try:
          body = response.json()
      except ValueError:
          return {}
      return body if isinstance(body, dict) else {}


  def is_lost(response: httpx2.Response) -> bool:
      """True for a 5xx response that can follow a refresh that took effect."""
      if response.status_code < 500:
          return False
      refused = (
          response.status_code == 503
          and error_body(response).get("type") == "error"
          and "retry-after" in response.headers
      )
      return not refused


  def hold_error(connection_id: str, reason: str) -> RefreshOnHoldError:
      return RefreshOnHoldError(
          f"Connection {connection_id} is on hold. {reason} Don't send its refresh token"
          " again: that can end the customer's link. See"
          ' "If a refresh fails" in the Linked billing docs.'
      )


  def refresh_connection(connection_id: str, *, force: bool = False) -> tuple[str, int]:
      """Returns a current access token and its expiry time in Unix seconds.

      Call this from your schedule. Pass force=True to refresh a token that isn't
      close to its expiry. Raises RefreshOnHoldError when the refresh token must not be
      sent again, and httpx2.HTTPStatusError for a refusal that keeps it.
      """
      # 이 잠금은 단일 프로세스 내에서만 작동합니다.
      with connection_locks[connection_id]:
          tokens = load_tokens(connection_id)
          if tokens.on_hold:
              raise hold_error(connection_id, f"Reason: {tokens.hold_reason}.")
          if not force and tokens.expires_at - time.time() > REFRESH_MARGIN_SECONDS:
              return tokens.access_token, tokens.expires_at
          request = {
              "grant_type": "refresh_token",
              "refresh_token": tokens.refresh_token,
              "client_id": CLIENT_ID,
              "client_assertion_type": JWT_BEARER,
              "client_assertion": client_assertion(),
          }
          # 먼저 보류를 설정하세요. 그래야 갱신 도중 프로세스가 중지되어도 보류가 유지됩니다.
          held = replace(tokens, on_hold=True, hold_reason="lost")
          save_tokens(connection_id, held)
          issued_at = int(time.time())
          started = time.monotonic()
          # 재시도를 추가하지 마세요. 늦은 재시도는 고객의 연결을 종료시킵니다.
          try:
              response = httpx2.post(TOKEN_URL, json=request, timeout=REQUEST_TIMEOUT)
              lost = is_lost(response)
          except (httpx2.ConnectError, httpx2.ConnectTimeout):
              # 리프레시 토큰이 이 프로세스를 벗어나지 않았으므로 보류를 해제합니다.
              save_tokens(connection_id, tokens)
              raise
          except httpx2.TransportError:
              lost = True
          if lost:
              if time.monotonic() - started > SECOND_REQUEST_DEADLINE_SECONDS:
                  raise hold_error(connection_id, "A refresh got no usable answer.")
              try:
                  response = httpx2.post(TOKEN_URL, json=request, timeout=REQUEST_TIMEOUT)
              except httpx2.TransportError:
                  raise hold_error(
                      connection_id, "Two refreshes got no answer."
                  ) from None
              if response.status_code != 200:
                  raise hold_error(connection_id, "The second refresh failed.")
          if error_body(response).get("error") == "invalid_grant":
              save_tokens(connection_id, replace(held, hold_reason="invalid_grant"))
              raise hold_error(connection_id, "The refresh returned invalid_grant.")
          if response.status_code != 200:
              # 리프레시 토큰을 유지하는 거부이므로 보류를 해제합니다.
              save_tokens(connection_id, tokens)
              response.raise_for_status()
          body = response.json()
          tokens = ConnectionTokens(
              refresh_token=body["refresh_token"],
              access_token=body["access_token"],
              expires_at=issued_at + body["expires_in"],
              refresh_expires_at=issued_at + body["refresh_token_expires_in"],
          )
          # 쓰기만 재시도하세요. 다시 갱신하지 마세요.
          for attempt in range(5):
              try:
                  save_tokens(connection_id, tokens)
                  return tokens.access_token, tokens.expires_at
              except OSError:  # your secret store's error type
                  if attempt < 4:
                      time.sleep(2**attempt)
          error = hold_error(
              connection_id,
              "The refresh succeeded, but the new tokens could not be saved.",
          )
          error.new_tokens = tokens
          raise error
  ```

  ```typescript TypeScript
  const connectionLocks = new Map<string, Promise<unknown>>();

  function withConnectionLock<T>(connectionId: string, work: () => Promise<T>): Promise<T> {
    const result = (connectionLocks.get(connectionId) ?? Promise.resolve()).then(work, work);
    connectionLocks.set(
      connectionId,
      result.catch(() => {})
    );
    return result;
  }

  class NotSent extends Error {}

  interface TokenResponse {
    status: number;
    headers: IncomingHttpHeaders;
    text: string;
  }

  function post(body: string): Promise<TokenResponse> {
    return new Promise((resolve, reject) => {
      let connected = false;
      const req = request(
        TOKEN_URL,
        {
          method: "POST",
          agent: false, // a new connection for each request
          headers: { "content-type": "application/json" },
          signal: AbortSignal.timeout(10_000)
        },
        (response) => {
          let text = "";
          response.setEncoding("utf8");
          response.on("data", (chunk: string) => (text += chunk));
          response.on("end", () =>
            resolve({ status: response.statusCode!, headers: response.headers, text })
          );
          response.on("error", reject);
        }
      );
      const connectTimer = setTimeout(
        () => req.destroy(new Error("No connection in 2 seconds")),
        2_000
      );
      req.on("socket", (socket) =>
        socket.once("secureConnect", () => {
          connected = true;
          clearTimeout(connectTimer);
        })
      );
      req.on("error", (error) => {
        clearTimeout(connectTimer);
        reject(connected ? error : new NotSent(error.message, { cause: error }));
      });
      req.end(body);
    });
  }

  function errorBody(response: TokenResponse): Record<string, unknown> {
    try {
      const body: unknown = JSON.parse(response.text);
      return typeof body === "object" && body !== null ? (body as Record<string, unknown>) : {};
    } catch {
      return {};
    }
  }

  /** True for a 5xx response that can follow a refresh that took effect. */
  function isLost(response: TokenResponse): boolean {
    if (response.status < 500) {
      return false;
    }
    const refused =
      response.status === 503 &&
      errorBody(response).type === "error" &&
      "retry-after" in response.headers;
    return !refused;
  }

  function holdError(
    connectionId: string,
    reason: string,
    newTokens?: ConnectionTokens
  ): RefreshOnHoldError {
    return new RefreshOnHoldError(
      `Connection ${connectionId} is on hold. ${reason} Don't send its refresh token again: ` +
        'that can end the customer\'s link. See "If a refresh fails" in the Linked billing docs.',
      newTokens
    );
  }

  /**
   * Returns a current access token and its expiry time in Unix seconds.
   *
   * Call this from your schedule. Pass force: true to refresh a token that isn't
   * close to its expiry. Throws RefreshOnHoldError when the refresh token must not be
   * sent again, and an Error for a refusal that keeps it.
   */
  function refreshConnection(connectionId: string, { force = false } = {}) {
    // 이 잠금은 단일 프로세스 내에서만 작동합니다.
    return withConnectionLock(connectionId, async () => {
      const tokens = await loadTokens(connectionId);
      if (tokens.onHold) {
        throw holdError(connectionId, `Reason: ${tokens.holdReason}.`);
      }
      if (!force && tokens.expiresAt - Date.now() / 1000 > REFRESH_MARGIN_SECONDS) {
        return { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt };
      }
      const body = JSON.stringify({
        grant_type: "refresh_token",
        refresh_token: tokens.refreshToken,
        client_id: CLIENT_ID,
        client_assertion_type: JWT_BEARER,
        client_assertion: await clientAssertion()
      });
      // 갱신 도중 프로세스가 중지되어도 보류가 유지되도록 먼저 보류를 설정합니다.
      const held: ConnectionTokens = { ...tokens, onHold: true, holdReason: "lost" };
      await saveTokens(connectionId, held);
      const issuedAt = Math.floor(Date.now() / 1000);
      const started = performance.now();
      // 재시도를 추가하지 마세요: 늦은 재시도는 고객의 연결을 종료시킵니다.
      let response: TokenResponse | undefined;
      try {
        response = await post(body);
      } catch (error) {
        if (error instanceof NotSent) {
          // 리프레시 토큰이 이 프로세스를 벗어나지 않았으므로 보류를 해제합니다.
          await saveTokens(connectionId, tokens);
          throw error;
        }
      }
      if (!response || isLost(response)) {
        if (performance.now() - started > SECOND_REQUEST_DEADLINE_MS) {
          throw holdError(connectionId, "A refresh got no usable answer.");
        }
        try {
          response = await post(body);
        } catch {
          throw holdError(connectionId, "Two refreshes got no answer.");
        }
        if (response.status !== 200) {
          throw holdError(connectionId, "The second refresh failed.");
        }
      }
      if (errorBody(response).error === "invalid_grant") {
        await saveTokens(connectionId, { ...held, holdReason: "invalid_grant" });
        throw holdError(connectionId, "The refresh returned invalid_grant.");
      }
      if (response.status !== 200) {
        // 리프레시 토큰을 유지하는 거부이므로 보류를 해제합니다.
        await saveTokens(connectionId, tokens);
        throw new Error(`Refresh failed: ${response.status} ${response.text}`);
      }
      const answer = JSON.parse(response.text);
      const newTokens: ConnectionTokens = {
        refreshToken: answer.refresh_token,
        accessToken: answer.access_token,
        expiresAt: issuedAt + answer.expires_in,
        refreshExpiresAt: issuedAt + answer.refresh_token_expires_in
      };
      // 쓰기만 재시도하세요. 다시 갱신하지 마세요.
      for (let attempt = 0; attempt < 5; attempt++) {
        try {
          await saveTokens(connectionId, newTokens);
          return { accessToken: newTokens.accessToken, expiresAt: newTokens.expiresAt };
        } catch {
          // 쓰기 실패
          if (attempt < 4) {
            await new Promise((wake) => setTimeout(wake, 2 ** attempt * 1000));
          }
        }
      }
      throw holdError(
        connectionId,
        "The refresh succeeded, but the new tokens could not be saved.",
        newTokens
      );
    });
  }
  ```

  ```csharp C#
  static partial class Connections
  {
      static readonly ConcurrentDictionary<string, SemaphoreSlim> ConnectionLocks = new();

      static readonly HttpClient Http = new(new SocketsHttpHandler
      {
          ConnectTimeout = TimeSpan.FromSeconds(2),
          AllowAutoRedirect = false,
          PooledConnectionLifetime = TimeSpan.Zero, // a new connection for each request
      })
      { Timeout = Timeout.InfiniteTimeSpan }; // Post sets the 10-second timeout

      static async Task<(HttpResponseMessage? Response, string Body, Exception? Error, bool Connected)> Post(
          string body)
      {
          using var request = new HttpRequestMessage(HttpMethod.Post, TokenUrl)
          {
              Content = new StringContent(body, Encoding.UTF8, "application/json"),
          };
          using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
          try
          {
              var response = await Http.SendAsync(request, timeout.Token);
              return (response, await response.Content.ReadAsStringAsync(timeout.Token), null, true);
          }
          catch (HttpRequestException e) when (e.HttpRequestError is HttpRequestError.ConnectionError
              or HttpRequestError.NameResolutionError or HttpRequestError.SecureConnectionError)
          {
              return (null, "", e, false);
          }
          catch (TaskCanceledException e) when (!timeout.IsCancellationRequested)
          {
              return (null, "", e, false); // the 2-second connect timeout
          }
          catch (Exception e) when (e is HttpRequestException or TaskCanceledException)
          {
              return (null, "", e, true); // a dropped connection or a timeout
          }
      }

      static JsonElement ErrorBody(string body)
      {
          try
          {
              using var document = JsonDocument.Parse(body);
              var parsed = document.RootElement;
              return parsed.ValueKind == JsonValueKind.Object ? parsed.Clone() : default;
          }
          catch (JsonException)
          {
              return default;
          }
      }

      static string? ErrorField(string body, string name) =>
          ErrorBody(body) is { ValueKind: JsonValueKind.Object } error && error.TryGetProperty(name, out var value)
              ? value.ToString()
              : null;

      /// <summary>적용된 갱신 뒤에 올 수 있는 5xx 응답이면 true입니다.</summary>
      static bool IsLost(HttpResponseMessage response, string body)
      {
          if ((int)response.StatusCode < 500) return false;
          var refused = (int)response.StatusCode == 503
              && ErrorField(body, "type") == "error"
              && response.Headers.Contains("retry-after");
          return !refused;
      }

      static RefreshOnHoldException HoldError(string connectionId, string reason) => new(
          $"Connection {connectionId} is on hold. {reason} Don't send its refresh token again: " +
          "that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs.");

      /// <summary>
      /// 현재 액세스 토큰과 만료 시각(Unix 초)을 반환합니다.
      /// 스케줄에서 호출하세요. 만료가 임박하지 않은 토큰을 갱신하려면
      /// force: true를 전달하세요. 리프레시 토큰을 다시 보내면 안 될 때 RefreshOnHoldException을,
      /// 토큰이 유지되는 거부에는 HttpRequestException을 throw합니다.
      /// </summary>
      public static async Task<(string AccessToken, long ExpiresAt)> RefreshConnection(
          string connectionId, bool force = false)
      {
          // 이 잠금은 단일 프로세스 안에서만 동작합니다.
          var connectionLock = ConnectionLocks.GetOrAdd(connectionId, _ => new SemaphoreSlim(1, 1));
          await connectionLock.WaitAsync();
          try
          {
              var tokens = await LoadTokens(connectionId);
              if (tokens.OnHold) throw HoldError(connectionId, $"Reason: {tokens.HoldReason}.");
              if (!force && tokens.ExpiresAt - DateTimeOffset.UtcNow.ToUnixTimeSeconds() > RefreshMarginSeconds)
              {
                  return (tokens.AccessToken, tokens.ExpiresAt);
              }
              var request = JsonSerializer.Serialize(new Dictionary<string, string>
              {
                  ["grant_type"] = "refresh_token",
                  ["refresh_token"] = tokens.RefreshToken,
                  ["client_id"] = ClientId,
                  ["client_assertion_type"] = JwtBearer,
                  ["client_assertion"] = ClientAssertion(),
              });
              // 갱신 도중 프로세스가 멈춰도 보류가 남도록 먼저 보류를 겁니다.
              var held = tokens with { OnHold = true, HoldReason = "lost" };
              await SaveTokens(connectionId, held);
              var issuedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
              var started = Stopwatch.StartNew();
              // 재시도를 추가하지 마세요. 늦은 재시도는 고객의 연결을 끊습니다.
              var (response, body, error, connected) = await Post(request);
              if (!connected)
              {
                  // 리프레시 토큰이 이 프로세스를 벗어나지 않았으므로 보류를 해제합니다.
                  await SaveTokens(connectionId, tokens);
                  throw new HttpRequestException("Couldn't connect to auth.claude.com.", error);
              }
              if (response is null || IsLost(response, body))
              {
                  if (started.Elapsed > SecondRequestDeadline)
                      throw HoldError(connectionId, "A refresh got no usable answer.");
                  (response, body, _, _) = await Post(request);
                  if (response is null) throw HoldError(connectionId, "Two refreshes got no answer.");
                  if ((int)response.StatusCode != 200) throw HoldError(connectionId, "The second refresh failed.");
              }
              if (ErrorField(body, "error") == "invalid_grant")
              {
                  await SaveTokens(connectionId, held with { HoldReason = "invalid_grant" });
                  throw HoldError(connectionId, "The refresh returned invalid_grant.");
              }
              if ((int)response.StatusCode != 200)
              {
                  // 리프레시 토큰이 유지되는 거부이므로 보류를 해제합니다.
                  await SaveTokens(connectionId, tokens);
                  throw new HttpRequestException($"Refresh failed: {(int)response.StatusCode} {body}",
                      null, response.StatusCode);
              }
              using var document = JsonDocument.Parse(body);
              var answer = document.RootElement;
              var newTokens = new ConnectionTokens(
                  RefreshToken: answer.GetProperty("refresh_token").GetString()!,
                  AccessToken: answer.GetProperty("access_token").GetString()!,
                  ExpiresAt: issuedAt + answer.GetProperty("expires_in").GetInt64(),
                  RefreshExpiresAt: issuedAt + answer.GetProperty("refresh_token_expires_in").GetInt64());
              // 쓰기만 재시도하세요. 다시 갱신하지 마세요.
              for (var attempt = 0; attempt < 5; attempt++)
              {
                  try
                  {
                      await SaveTokens(connectionId, newTokens);
                      return (newTokens.AccessToken, newTokens.ExpiresAt);
                  }
                  catch (IOException) // your secret store's error type
                  {
                      if (attempt < 4) await Task.Delay(TimeSpan.FromSeconds(1 << attempt));
                  }
              }
              throw new RefreshOnHoldException(HoldError(connectionId,
                  "The refresh succeeded, but the new tokens could not be saved.").Message)
              { NewTokens = newTokens };
          }
          finally
          {
              connectionLock.Release();
          }
      }
  }
  ```

  ```go Go
  var connectionLocks sync.Map

  type tokenResponse struct {
  	status int
  	header http.Header
  	body   []byte
  }

  // post는 갱신 요청을 보냅니다. 요청이 전송되지 않았으면 connected는 false입니다.
  func post(body []byte) (response *tokenResponse, connected bool, err error) {
  	request, err := http.NewRequest(http.MethodPost, tokenURL, bytes.NewReader(body))
  	if err != nil {
  		return nil, false, err
  	}
  	request.Header.Set("content-type", "application/json")
  	trace := &httptrace.ClientTrace{GotConn: func(httptrace.GotConnInfo) { connected = true }}
  	request = request.WithContext(httptrace.WithClientTrace(request.Context(), trace))
  	answer, err := httpClient.Do(request)
  	if err != nil {
  		return nil, connected, err
  	}
  	defer answer.Body.Close()
  	data, err := io.ReadAll(answer.Body)
  	if err != nil {
  		return nil, true, err
  	}
  	return &tokenResponse{answer.StatusCode, answer.Header, data}, true, nil
  }

  func errorBody(response *tokenResponse) map[string]any {
  	var body map[string]any
  	if json.Unmarshal(response.body, &body) != nil {
  		return map[string]any{}
  	}
  	return body
  }

  // isLost는 갱신이 적용된 후에도 올 수 있는 5xx 응답일 때 true입니다.
  func isLost(response *tokenResponse) bool {
  	if response.status < 500 {
  		return false
  	}
  	refused := response.status == 503 &&
  		errorBody(response)["type"] == "error" &&
  		response.header.Get("retry-after") != ""
  	return !refused
  }

  func holdError(connectionID, reason string) *RefreshOnHoldError {
  	return &RefreshOnHoldError{Message: fmt.Sprintf("connection %s is on hold. %s Don't send its refresh token "+
  		"again: that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs.",
  		connectionID, reason)}
  }

  // refreshConnection은 현재 액세스 토큰과 그 만료 시각(Unix
  // 초)을 반환합니다. 일정에 따라 호출하세요. 만료가 임박하지 않은 토큰을 갱신하려면
  // force=true를 전달하세요. 리프레시 토큰을 다시 보내면 안 될 때는 *RefreshOnHoldError를,
  // 토큰이 유지되는 거부에는 다른 오류를 반환합니다.
  func refreshConnection(connectionID string, force bool) (string, int64, error) {
  	// 이 잠금은 단일 프로세스 내에서만 동작합니다.
  	lock, _ := connectionLocks.LoadOrStore(connectionID, &sync.Mutex{})
  	lock.(*sync.Mutex).Lock()
  	defer lock.(*sync.Mutex).Unlock()

  	tokens, err := loadTokens(connectionID)
  	if err != nil {
  		return "", 0, err
  	}
  	if tokens.OnHold {
  		return "", 0, holdError(connectionID, "Reason: "+tokens.HoldReason+".")
  	}
  	if !force && time.Until(time.Unix(tokens.ExpiresAt, 0)) > refreshMargin {
  		return tokens.AccessToken, tokens.ExpiresAt, nil
  	}
  	assertion, err := clientAssertion()
  	if err != nil {
  		return "", 0, err
  	}
  	body, err := json.Marshal(map[string]string{
  		"grant_type":            "refresh_token",
  		"refresh_token":         tokens.RefreshToken,
  		"client_id":             clientID,
  		"client_assertion_type": jwtBearer,
  		"client_assertion":      assertion,
  	})
  	if err != nil {
  		return "", 0, err
  	}
  	// 갱신 중 프로세스가 중단되어도 보류가 유지되도록 먼저 보류합니다.
  	held := tokens
  	held.OnHold, held.HoldReason = true, "lost"
  	if err := saveTokens(connectionID, held); err != nil {
  		return "", 0, err
  	}
  	issuedAt := time.Now().Unix()
  	started := time.Now()
  	// 재시도를 추가하지 마세요. 늦은 재시도는 고객의 연결을 끊습니다.
  	response, connected, err := post(body)
  	if err != nil && !connected {
  		// 리프레시 토큰이 이 프로세스를 벗어나지 않았으므로 보류를 해제합니다.
  		if saveErr := saveTokens(connectionID, tokens); saveErr != nil {
  			return "", 0, saveErr
  		}
  		return "", 0, err
  	}
  	if err != nil || isLost(response) {
  		if time.Since(started) > secondRequestDeadline {
  			return "", 0, holdError(connectionID, "A refresh got no usable answer.")
  		}
  		if response, _, err = post(body); err != nil {
  			return "", 0, holdError(connectionID, "Two refreshes got no answer.")
  		}
  		if response.status != 200 {
  			return "", 0, holdError(connectionID, "The second refresh failed.")
  		}
  	}
  	if errorBody(response)["error"] == "invalid_grant" {
  		held.HoldReason = "invalid_grant"
  		if err := saveTokens(connectionID, held); err != nil {
  			return "", 0, err
  		}
  		return "", 0, holdError(connectionID, "The refresh returned invalid_grant.")
  	}
  	if response.status != 200 {
  		// 리프레시 토큰이 유지되는 거부이므로 보류를 해제합니다.
  		if err := saveTokens(connectionID, tokens); err != nil {
  			return "", 0, err
  		}
  		return "", 0, fmt.Errorf("refresh failed: %d %s", response.status, response.body)
  	}
  	var answer struct {
  		AccessToken           string `json:"access_token"`
  		RefreshToken          string `json:"refresh_token"`
  		ExpiresIn             int64  `json:"expires_in"`
  		RefreshTokenExpiresIn int64  `json:"refresh_token_expires_in"`
  	}
  	if err := json.Unmarshal(response.body, &answer); err != nil {
  		return "", 0, holdError(connectionID, "The refresh answer could not be read.")
  	}
  	tokens = ConnectionTokens{
  		RefreshToken:     answer.RefreshToken,
  		AccessToken:      answer.AccessToken,
  		ExpiresAt:        issuedAt + answer.ExpiresIn,
  		RefreshExpiresAt: issuedAt + answer.RefreshTokenExpiresIn,
  	}
  	// 쓰기만 재시도하세요. 다시 갱신하지 마세요.
  	for attempt := range 5 {
  		if err := saveTokens(connectionID, tokens); err == nil {
  			return tokens.AccessToken, tokens.ExpiresAt, nil
  		}
  		if attempt < 4 {
  			time.Sleep(time.Second << attempt)
  		}
  	}
  	hold := holdError(connectionID, "The refresh succeeded, but the new tokens could not be saved.")
  	hold.NewTokens = &tokens
  	return "", 0, hold
  }
  ```

  ```java Java
  final Map<String, ReentrantLock> connectionLocks = new ConcurrentHashMap<>();
  final ObjectMapper mapper = new ObjectMapper();
  final HttpClient http = HttpClient.newBuilder()
      .connectTimeout(Duration.ofSeconds(2))
      .followRedirects(HttpClient.Redirect.NEVER)
      .build();

  HttpResponse<String> post(String body) throws IOException, InterruptedException {
      var request = HttpRequest.newBuilder(TOKEN_URL)
          .header("content-type", "application/json")
          .timeout(Duration.ofSeconds(10))
          .POST(HttpRequest.BodyPublishers.ofString(body))
          .build();
      return http.send(request, HttpResponse.BodyHandlers.ofString());
  }

  JsonNode errorBody(HttpResponse<String> response) {
      try {
          return mapper.readTree(response.body());
      } catch (IOException _) {
          return mapper.createObjectNode();
      }
  }

  /** True for a 5xx response that can follow a refresh that took effect. */
  boolean isLost(HttpResponse<String> response) {
      if (response.statusCode() < 500) {
          return false;
      }
      boolean refused = response.statusCode() == 503
          && errorBody(response).path("type").asText().equals("error")
          && response.headers().firstValue("retry-after").isPresent();
      return !refused;
  }

  RefreshOnHoldException holdError(String connectionId, String reason) {
      return new RefreshOnHoldException("Connection " + connectionId + " is on hold. " + reason
          + " Don't send its refresh token again: that can end the customer's link."
          + " See \"If a refresh fails\" in the Linked billing docs.");
  }

  /**
   * Returns a current access token and its expiry time in Unix seconds.
   * Call this from your schedule. Pass force = true to refresh a token that isn't
   * close to its expiry. Throws RefreshOnHoldException when the refresh token must not be
   * sent again, and IOException for a refusal that keeps it.
   */
  AccessToken refreshConnection(String connectionId, boolean force)
          throws IOException, InterruptedException {
      // 이 잠금은 단일 프로세스 내에서만 작동합니다.
      var lock = connectionLocks.computeIfAbsent(connectionId, id -> new ReentrantLock());
      lock.lock();
      try {
          var tokens = loadTokens(connectionId);
          if (tokens.onHold()) {
              throw holdError(connectionId, "Reason: " + tokens.holdReason() + ".");
          }
          if (!force && tokens.expiresAt() - Instant.now().getEpochSecond() > REFRESH_MARGIN_SECONDS) {
              return new AccessToken(tokens.accessToken(), tokens.expiresAt());
          }
          var request = mapper.createObjectNode()
              .put("grant_type", "refresh_token")
              .put("refresh_token", tokens.refreshToken())
              .put("client_id", CLIENT_ID)
              .put("client_assertion_type", JWT_BEARER)
              .put("client_assertion", clientAssertion())
              .toString();
          // 먼저 보류를 설정하세요. 갱신 도중 프로세스가 중단되어도 보류가 유지되도록 하기 위함입니다.
          var held = tokens.withHold("lost");
          saveTokens(connectionId, held);
          long issuedAt = Instant.now().getEpochSecond();
          long started = System.nanoTime();
          // 재시도를 추가하지 마세요. 늦은 재시도는 고객의 연결을 종료시킵니다.
          HttpResponse<String> response = null;
          try {
              response = post(request);
          } catch (ConnectException | HttpConnectTimeoutException | SSLHandshakeException e) {
              // 리프레시 토큰이 이 프로세스를 벗어나지 않았으므로 보류를 해제합니다.
              saveTokens(connectionId, tokens);
              throw e;
          } catch (IOException _) {
              // 연결이 끊겼거나 제시간에 응답이 오지 않았습니다.
          }
          if (response == null || isLost(response)) {
              if (Duration.ofNanos(System.nanoTime() - started).compareTo(SECOND_REQUEST_DEADLINE) > 0) {
                  throw holdError(connectionId, "A refresh got no usable answer.");
              }
              try {
                  response = post(request);
              } catch (IOException _) {
                  throw holdError(connectionId, "Two refreshes got no answer.");
              }
              if (response.statusCode() != 200) {
                  throw holdError(connectionId, "The second refresh failed.");
              }
          }
          if (errorBody(response).path("error").asText().equals("invalid_grant")) {
              saveTokens(connectionId, held.withHold("invalid_grant"));
              throw holdError(connectionId, "The refresh returned invalid_grant.");
          }
          if (response.statusCode() != 200) {
              // 리프레시 토큰을 유지하는 거부이므로 보류를 해제합니다.
              saveTokens(connectionId, tokens);
              throw new IOException("Refresh failed: " + response.statusCode() + " " + response.body());
          }
          var answer = mapper.readTree(response.body());
          var newTokens = new ConnectionTokens(
              answer.get("refresh_token").asText(),
              answer.get("access_token").asText(),
              issuedAt + answer.get("expires_in").asLong(),
              issuedAt + answer.get("refresh_token_expires_in").asLong(),
              false,
              null);
          // 쓰기만 재시도하세요. 다시 갱신하지 마세요.
          for (int attempt = 0; attempt < 5; attempt++) {
              try {
                  saveTokens(connectionId, newTokens);
                  return new AccessToken(newTokens.accessToken(), newTokens.expiresAt());
              } catch (IOException _) { // your secret store's error type
                  if (attempt < 4) {
                      Thread.sleep(Duration.ofSeconds(1L << attempt));
                  }
              }
          }
          var error = holdError(connectionId, "The refresh succeeded, but the new tokens could not be saved.");
          error.newTokens = newTokens;
          throw error;
      } finally {
          lock.unlock();
      }
  }
  ```

  ```php PHP
  /**
   * Sends the refresh. Returns a string, curl's error, when the request never left this process.
   *
   * @return array{status: int, headers: list<string>, body: string}|false|string false: no answer
   */
  function post(string $body): array|false|string
  {
      $headers = [];
      $curl = curl_init(TOKEN_URL);
      curl_setopt_array($curl, [
          CURLOPT_POST => true,
          CURLOPT_POSTFIELDS => $body,
          CURLOPT_HTTPHEADER => ['content-type: application/json'],
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_CONNECTTIMEOUT => 2,
          CURLOPT_TIMEOUT => 10,
          CURLOPT_FOLLOWLOCATION => false,
          CURLOPT_FORBID_REUSE => true, // a new connection for each request
          CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
              $headers[] = strtolower(trim($line));
              return strlen($line);
          },
      ]);
      $text = curl_exec($curl);
      if (!is_string($text)) {
          // 아직 TLS 연결이 없다는 것은 아무것도 전송되지 않았다는 의미입니다.
          return curl_getinfo($curl, CURLINFO_APPCONNECT_TIME_T) > 0 ? false : curl_error($curl);
      }
      return ['status' => curl_getinfo($curl, CURLINFO_RESPONSE_CODE), 'headers' => $headers, 'body' => $text];
  }

  /**
   * @param array{status: int, headers: list<string>, body: string} $response
   * @return array<mixed>
   */
  function errorBody(array $response): array
  {
      $body = json_decode($response['body'], associative: true);
      return is_array($body) ? $body : [];
  }

  /**
   * True for a 5xx response that can follow a refresh that took effect.
   *
   * @param array{status: int, headers: list<string>, body: string} $response
   */
  function isLost(array $response): bool
  {
      if ($response['status'] < 500) {
          return false;
      }
      $refused = $response['status'] === 503
          && (errorBody($response)['type'] ?? null) === 'error'
          && preg_grep('/^retry-after:/', $response['headers']);
      return !$refused;
  }

  function holdError(string $connectionId, string $reason): RefreshOnHoldException
  {
      return new RefreshOnHoldException(
          "Connection {$connectionId} is on hold. {$reason} Don't send its refresh token again: "
          . "that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs."
      );
  }

  /**
   * Returns a current access token and its expiry time in Unix seconds.
   *
   * Call this from your schedule. Pass force: true to refresh a token that isn't
   * close to its expiry. Throws RefreshOnHoldException when the refresh token must not be
   * sent again, and \RuntimeException for a refusal that keeps it.
   *
   * @return array{string, int}
   */
  function refreshConnection(string $connectionId, bool $force = false): array
  {
      // 이 잠금은 단일 머신에서만 동작합니다.
      $lock = fopen(sys_get_temp_dir() . '/refresh-' . hash('sha256', $connectionId) . '.lock', 'c')
          ?: throw new \RuntimeException('Cannot open the lock file');
      flock($lock, LOCK_EX);
      try {
          $tokens = loadTokens($connectionId);
          if ($tokens->onHold) {
              throw holdError($connectionId, "Reason: {$tokens->holdReason}.");
          }
          if (!$force && $tokens->expiresAt - time() > REFRESH_MARGIN_SECONDS) {
              return [$tokens->accessToken, $tokens->expiresAt];
          }
          $request = json_encode([
              'grant_type' => 'refresh_token',
              'refresh_token' => $tokens->refreshToken,
              'client_id' => CLIENT_ID,
              'client_assertion_type' => JWT_BEARER,
              'client_assertion' => clientAssertion(),
          ], JSON_THROW_ON_ERROR);
          // 먼저 보류를 걸어 두세요. 그래야 갱신 도중 프로세스가 중단되어도 보류가 유지됩니다.
          $held = $tokens->withHold('lost');
          saveTokens($connectionId, $held);
          $issuedAt = time();
          $started = hrtime(true);
          // 재시도를 추가하지 마세요. 늦은 재시도는 고객의 연결을 끊습니다.
          $response = post($request);
          if (is_string($response)) {
              // 리프레시 토큰이 이 프로세스를 벗어난 적이 없으므로 보류를 해제합니다.
              saveTokens($connectionId, $tokens);
              throw new \RuntimeException("Could not connect to auth.claude.com: {$response}");
          }
          if ($response === false || isLost($response)) {
              if ((hrtime(true) - $started) / 1e9 > SECOND_REQUEST_DEADLINE_SECONDS) {
                  throw holdError($connectionId, 'A refresh got no usable answer.');
              }
              $response = post($request);
              if (!is_array($response)) {
                  throw holdError($connectionId, 'Two refreshes got no answer.');
              }
              if ($response['status'] !== 200) {
                  throw holdError($connectionId, 'The second refresh failed.');
              }
          }
          if ((errorBody($response)['error'] ?? null) === 'invalid_grant') {
              saveTokens($connectionId, $held->withHold('invalid_grant'));
              throw holdError($connectionId, 'The refresh returned invalid_grant.');
          }
          if ($response['status'] !== 200) {
              // 리프레시 토큰을 유지하는 거부이므로 보류를 해제합니다.
              saveTokens($connectionId, $tokens);
              throw new \RuntimeException("Refresh failed: {$response['status']} {$response['body']}");
          }
          /**
           * @var array{
           *     access_token: string,
           *     refresh_token: string,
           *     expires_in: int,
           *     refresh_token_expires_in: int,
           * } $answer
           */
          $answer = json_decode($response['body'], associative: true, flags: JSON_THROW_ON_ERROR);
          $newTokens = new ConnectionTokens(
              refreshToken: $answer['refresh_token'],
              accessToken: $answer['access_token'],
              expiresAt: $issuedAt + $answer['expires_in'],
              refreshExpiresAt: $issuedAt + $answer['refresh_token_expires_in'],
          );
          // 쓰기만 재시도하세요. 다시 갱신하지 마세요.
          for ($attempt = 0; $attempt < 5; $attempt++) {
              try {
                  saveTokens($connectionId, $newTokens);
                  return [$newTokens->accessToken, $newTokens->expiresAt];
              } catch (\RuntimeException) { // your secret store's error type
                  if ($attempt < 4) {
                      sleep(2 ** $attempt);
                  }
              }
          }
          $error = holdError($connectionId, 'The refresh succeeded, but the new tokens could not be saved.');
          $error->newTokens = $newTokens;
          throw $error;
      } finally {
          flock($lock, LOCK_UN);
          fclose($lock);
      }
  }
  ```

  ```ruby Ruby
  CONNECTION_LOCKS = Hash.new { |locks, connection_id| locks[connection_id] = Mutex.new }
  LOCKS_GUARD = Mutex.new

  # 연결할 수 없으면 요청이 전송되기 전에 예외를 발생시킵니다.
  def open_connection
    Net::HTTP.start(TOKEN_URL.host, TOKEN_URL.port, use_ssl: true,
      open_timeout: 2, read_timeout: 10, write_timeout: 10, max_retries: 0)
  end

  def post(http, body)
    http.post(TOKEN_URL.path, body, "content-type" => "application/json")
  ensure
    http.finish
  end

  def error_body(response)
    body = JSON.parse(response.body.to_s)
    body.is_a?(Hash) ? body : {}
  rescue JSON::ParserError
    {}
  end

  # 적용된 갱신 이후에 발생할 수 있는 5xx 응답이면 true입니다.
  def lost?(response)
    return false if response.code.to_i < 500

    refused = response.code == "503" &&
      error_body(response)["type"] == "error" &&
      response.key?("retry-after")
    !refused
  end

  def hold_error(connection_id, reason)
    RefreshOnHoldError.new(
      "Connection #{connection_id} is on hold. #{reason} Don't send its refresh token again: " \
      "that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs."
    )
  end

  # 현재 액세스 토큰과 만료 시각(Unix 초)을 반환합니다.
  #
  # 스케줄에서 호출하세요. 만료가 임박하지 않은 토큰을 갱신하려면 force: true를 전달하세요.
  # 리프레시 토큰을 다시 보내면 안 되는 경우 RefreshOnHoldError를,
  # 토큰을 유지하는 거부의 경우 RuntimeError를 발생시킵니다.
  def refresh_connection(connection_id, force: false)
    # 이 잠금은 단일 프로세스 내에서만 작동합니다.
    LOCKS_GUARD.synchronize { CONNECTION_LOCKS[connection_id] }.synchronize do
      tokens = load_tokens(connection_id)
      raise hold_error(connection_id, "Reason: #{tokens.hold_reason}.") if tokens.on_hold
      if !force && tokens.expires_at - Time.now.to_i > REFRESH_MARGIN_SECONDS
        return tokens.access_token, tokens.expires_at
      end

      request = {
        grant_type: "refresh_token",
        refresh_token: tokens.refresh_token,
        client_id: CLIENT_ID,
        client_assertion_type: JWT_BEARER,
        client_assertion:
      }.to_json
      # 갱신 도중 프로세스가 중단되어도 보류가 유지되도록 먼저 보류를 설정합니다.
      held = tokens.with(on_hold: true, hold_reason: "lost")
      save_tokens(connection_id, held)
      issued_at = Time.now.to_i
      started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      # 재시도를 추가하지 마세요. 늦은 재시도는 고객의 연결을 종료시킵니다.
      begin
        http = open_connection
      rescue
        # 리프레시 토큰이 이 프로세스를 벗어나지 않았으므로 보류를 해제합니다.
        save_tokens(connection_id, tokens)
        raise
      end
      begin
        response = post(http, request)
        lost = lost?(response)
      rescue
        lost = true
      end
      if lost
        if Process.clock_gettime(Process::CLOCK_MONOTONIC) - started > SECOND_REQUEST_DEADLINE_SECONDS
          raise hold_error(connection_id, "A refresh got no usable answer.")
        end
        begin
          response = post(open_connection, request)
        rescue
          raise hold_error(connection_id, "Two refreshes got no answer.")
        end
        raise hold_error(connection_id, "The second refresh failed.") unless response.code == "200"
      end
      if error_body(response)["error"] == "invalid_grant"
        save_tokens(connection_id, held.with(hold_reason: "invalid_grant"))
        raise hold_error(connection_id, "The refresh returned invalid_grant.")
      end
      unless response.code == "200"
        # 리프레시 토큰을 유지하는 거부이므로 보류를 해제합니다.
        save_tokens(connection_id, tokens)
        raise "Refresh failed: #{response.code} #{response.body}"
      end
      body = JSON.parse(response.body)
      tokens = ConnectionTokens.new(
        refresh_token: body.fetch("refresh_token"),
        access_token: body.fetch("access_token"),
        expires_at: issued_at + body.fetch("expires_in"),
        refresh_expires_at: issued_at + body.fetch("refresh_token_expires_in")
      )
      # 쓰기만 재시도하세요. 다시 갱신하지 마세요.
      5.times do |attempt|
        save_tokens(connection_id, tokens)
        return tokens.access_token, tokens.expires_at
      rescue IOError, SystemCallError # your secret store's error types
        sleep(2**attempt) if attempt < 4
      end
      error = hold_error(connection_id, "The refresh succeeded, but the new tokens could not be saved.")
      error.new_tokens = tokens
      raise error
    end
  end
  ```
</CodeGroup>

### API 키가 프로세스에 도달할 수 있는 경우

이 섹션은 고객의 액세스 토큰과 함께 `ANTHROPIC_API_KEY`가 설정될 수 있는 프로세스에만 해당합니다. 다음 클라이언트는 토큰 대신 키를 보냅니다.

* `ant` CLI
* `ANTHROPIC_AUTH_TOKEN`에서 토큰을 읽는 SDK 클라이언트

생성 시 토큰을 전달받은 SDK 클라이언트는 토큰만 보냅니다. 다른 클라이언트는 둘 다 보낼 수 있습니다. 이 경우에도 키가 우선하며, 예외적으로 Models 엔드포인트에서는 요청이 거부될 수 있습니다. 키가 전송되면 Claude API는 키로 요청을 인증하므로 요청이 해당 고객으로 제한되지 않습니다.

이러한 프로세스에서의 보호 장치로, 각 요청에 `anthropic-user-profile-id` 헤더, `bill_to: "user_profile"`이 포함된 `billing_policy`, 그리고 `user-profiles-billing-2026-10-01` 베타 헤더를 함께 보내세요. 그러면 키와 함께 전송된 요청은 다음 결과 중 하나를 갖습니다.

* **헤더와 `bill_to: "user_profile"`이 있는 경우:** 실패하거나, 헤더가 지정한 고객에게 요금이 청구됩니다.
* **헤더만 있거나 둘 다 없는 경우:** Anthropic이 귀하에게 요금을 청구합니다.

### 각 새 액세스 토큰을 샌드박스에 쓸 때

백엔드는 귀하가 구축한 채널을 통해 각 새 토큰을 샌드박스 안의 코드로 보냅니다. 그 코드는 에이전트의 사용자로 실행되며, 모드 `0700`인 `credentials` 디렉터리에 토큰을 씁니다. 모드 `0600`으로 새 파일을 쓰고 이전 파일 위로 이름을 바꾸므로, 에이전트가 파일의 절반만 읽는 일이 없습니다. 다음 함수가 이를 수행합니다.

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    샌드박스에서 에이전트의 사용자로 실행되는 애플리케이션 코드로 파일을 쓰세요.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    샌드박스에서 에이전트의 사용자로 실행되는 애플리케이션 코드로 파일을 쓰세요.
  </CodeGroupItem>

  ```python Python
  import json
  import os
  import tempfile
  from pathlib import Path


  def write_credentials_file(
      config_dir: Path, profile: str, token: str, expires_at: int
  ) -> None:
      """Run this in the sandbox, as the agent's user."""
      credentials_dir = config_dir / "credentials"
      credentials_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
      body = {"type": "oauth_token", "access_token": token, "expires_at": expires_at}
      handle, temporary_path = tempfile.mkstemp(dir=credentials_dir)  # mode 0600
      with os.fdopen(handle, "w") as temporary_file:
          json.dump(body, temporary_file)
      os.replace(temporary_path, credentials_dir / f"{profile}.json")
  ```

  ```typescript TypeScript
  import { mkdir, rename, writeFile } from "node:fs/promises";
  import { join } from "node:path";

  /** Run this in the sandbox, as the agent's user. */
  async function writeCredentialsFile(
    configDir: string,
    profile: string,
    token: string,
    expiresAt: number
  ) {
    const credentialsDir = join(configDir, "credentials");
    await mkdir(credentialsDir, { mode: 0o700, recursive: true });
    const body = { type: "oauth_token", access_token: token, expires_at: expiresAt };
    const temporaryPath = join(credentialsDir, `.${crypto.randomUUID()}.tmp`);
    await writeFile(temporaryPath, JSON.stringify(body), { mode: 0o600, flag: "wx" });
    await rename(temporaryPath, join(credentialsDir, `${profile}.json`));
  }
  ```

  ```csharp C#
  using System.Text.Json;

  /// <summary>샌드박스에서 에이전트의 사용자로 이것을 실행하세요.</summary>
  static void WriteCredentialsFile(string configDir, string profile, string token, long expiresAt)
  {
      var credentialsDir = Path.Combine(configDir, "credentials");
      Directory.CreateDirectory(credentialsDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
      var body = new Dictionary<string, object>
      {
          ["type"] = "oauth_token",
          ["access_token"] = token,
          ["expires_at"] = expiresAt,
      };
      var temporaryPath = Path.Combine(credentialsDir, $".{Guid.NewGuid()}.tmp");
      using (var temporaryFile = new FileStream(temporaryPath, new FileStreamOptions
      {
          Mode = FileMode.CreateNew,
          Access = FileAccess.Write,
          UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite,
      }))
      {
          JsonSerializer.Serialize(temporaryFile, body);
      }
      File.Move(temporaryPath, Path.Combine(credentialsDir, $"{profile}.json"), overwrite: true);
  }
  ```

  ```go Go
  import (
  	"encoding/json"
  	"os"
  	"path/filepath"
  )

  // writeCredentialsFile은 샌드박스에서 에이전트의 사용자 권한으로 실행됩니다.
  func writeCredentialsFile(configDir, profile, token string, expiresAt int64) error {
  	credentialsDir := filepath.Join(configDir, "credentials")
  	if err := os.MkdirAll(credentialsDir, 0o700); err != nil {
  		return err
  	}
  	body, err := json.Marshal(map[string]any{"type": "oauth_token", "access_token": token, "expires_at": expiresAt})
  	if err != nil {
  		return err
  	}
  	temporaryFile, err := os.CreateTemp(credentialsDir, ".tmp-*") // mode 0600
  	if err != nil {
  		return err
  	}
  	defer os.Remove(temporaryFile.Name()) // does nothing once the rename is done
  	if _, err := temporaryFile.Write(body); err != nil {
  		temporaryFile.Close()
  		return err
  	}
  	if err := temporaryFile.Close(); err != nil {
  		return err
  	}
  	return os.Rename(temporaryFile.Name(), filepath.Join(credentialsDir, profile+".json"))
  }
  ```

  ```java Java
  import module java.base;
  import com.fasterxml.jackson.databind.ObjectMapper; // Jackson comes with the Anthropic SDK

  /** Run this in the sandbox, as the agent's user. */
  void writeCredentialsFile(Path configDir, String profile, String token, long expiresAt) throws IOException {
      var credentialsDir = Files.createDirectories(configDir.resolve("credentials"),
          PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
      var body = Map.of("type", "oauth_token", "access_token", token, "expires_at", expiresAt);
      var temporaryPath = Files.createTempFile(credentialsDir, ".", ".tmp"); // mode 0600
      Files.writeString(temporaryPath, new ObjectMapper().writeValueAsString(body));
      Files.move(temporaryPath, credentialsDir.resolve(profile + ".json"),
          StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
  }
  ```

  ```php PHP
  /** Run this in the sandbox, as the agent's user. */
  function writeCredentialsFile(string $configDir, string $profile, string $token, int $expiresAt): void
  {
      $credentialsDir = "{$configDir}/credentials";
      if (!is_dir($credentialsDir) && !mkdir($credentialsDir, 0700, recursive: true)) {
          throw new \RuntimeException("Cannot create {$credentialsDir}");
      }
      $credentials = ['type' => 'oauth_token', 'access_token' => $token, 'expires_at' => $expiresAt];
      $body = json_encode($credentials, JSON_THROW_ON_ERROR);
      $temporaryPath = tempnam($credentialsDir, '.tmp'); // mode 0600
      if ($temporaryPath === false || dirname($temporaryPath) !== realpath($credentialsDir)) {
          throw new \RuntimeException("Cannot create a file in {$credentialsDir}"); // tempnam can fall back to /tmp
      }
      $finalPath = "{$credentialsDir}/{$profile}.json";
      if (file_put_contents($temporaryPath, $body) === false || !rename($temporaryPath, $finalPath)) {
          throw new \RuntimeException("Cannot write the credentials for {$profile}");
      }
  }
  ```

  ```ruby Ruby
  require "fileutils"
  require "json"
  require "tempfile"

  # 샌드박스에서 에이전트의 사용자 권한으로 실행하세요.
  def write_credentials_file(config_dir, profile, token, expires_at)
    credentials_dir = File.join(config_dir, "credentials")
    FileUtils.mkdir_p(credentials_dir, mode: 0o700)
    body = { type: "oauth_token", access_token: token, expires_at: }
    temporary_file = Tempfile.create(".tmp", credentials_dir) # mode 0600
    temporary_file.write(body.to_json)
    temporary_file.close
    File.rename(temporary_file.path, File.join(credentials_dir, "#{profile}.json"))
  end
  ```
</CodeGroup>

갱신 후 몇 분 이내에 이전 토큰을 사용한 요청은 `401`을 받습니다. 그러면 클라이언트는 파일을 다시 읽고 새 토큰으로 요청을 보낼 수 있습니다. TypeScript 또는 C# SDK만 단독으로 사용하는 경우에는 해당 요청이 대신 실패합니다. 한 번 더 보내세요. 다음 요청은 새 토큰을 사용합니다. SDK는 또한 `expires_at` 이전 마지막 2분 동안(Java에서는 마지막 30초 동안) 파일을 다시 읽습니다.

### 에이전트를 위한 안내

* 갱신할 때 `scope` 매개변수를 보내지 마세요.
* 갱신할 때마다 파일에서 클라이언트 어설션을 다시 읽으세요.
* 새 토큰을 저장할 때는 `expires_in`과 `refresh_token_expires_in`을 사용하여 갱신을 보낸 시점부터 만료 시간을 계산하세요.
* 정지가 해제되면 `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`)이 `invalid_grant`인 경우에만 `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`)를 해제하세요.
* 샌드박스의 자격 증명 파일을 쓸 때는 `expires_at`까지 30초 넘게 남은 토큰을 쓰세요.

## 다음 단계

<CardGroup cols={2}>
  <Card title="앱 테스트 및 게시" icon="rocket" href="https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/test-and-publish">
    테스트 사용자를 추가하고, 앱을 게시하고, 앱을 변경하거나 삭제합니다
  </Card>

  <Card title="고객에게 표시되는 내용" icon="browser" href="https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    고객을 지원할 수 있도록 고객에게 표시되는 승인 페이지, 지출 한도 및 이메일을 확인합니다
  </Card>
</CardGroup>
