---
title: Usa una credenziale separata per ogni cliente
url: https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/credential-for-each-customer
description: Chiama Claude con il token di accesso OAuth di ciascun cliente, in modo che il codice che non controlli completamente possa addebitare solo quel cliente.
---

<Warning>
  Claude Platform OAuth è un Beta Service: software in anteprima fornito ai sensi del tuo accordo con Anthropic, come i [Termini di servizio commerciali](https://www.anthropic.com/legal/commercial-terms), e i [Termini specifici del servizio](https://www.anthropic.com/legal/service-specific-terms). Endpoint, parametri e comportamento possono cambiare durante la beta. Potrebbe non essere adatto all’uso in produzione.
</Warning>

Ogni cliente che colleghi con [Linked billing](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing) ha una propria credenziale: un “access token” (token di accesso) OAuth che può addebitare solo quel cliente. Usalo quando del codice che non controlli completamente chiama Claude per un cliente, ad esempio nella sandbox di un agente o in un deployment single-tenant. Un bug o una fuga di dati in quel codice potrà così addebitare solo quel cliente.

Se ogni richiesta che addebita un cliente proviene dal tuo back end, non hai bisogno di queste credenziali. [Addebita i clienti come tuo account di servizio operatore](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request) e salta questa pagina.

## Prima di iniziare

* **I token OAuth e l’ID di connessione del cliente:** Lo scambio del codice li ha restituiti quando hai [collegato il cliente](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#save-the-connection-and-its-tokens). Una connessione è il record che lega l’organizzazione Claude del cliente a uno dei tuoi [profili utente](https://platform.claude.com/docs/it/manage-claude/user-profiles).
* **Un refresh token:** [**Offline access**](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens) è attivo per la tua app e il cliente ha approvato `billing:attribution offline_access`. Un cliente che ha approvato senza `offline_access` ottiene un refresh token [approvando di nuovo](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again), il che sostituisce la sua connessione senza uno scollegamento.
* **Per gli esempi di aggiornamento:** Una client assertion: un JWT del tuo provider di identità per l’**Expected audience** della tua app, configurato come [autenticazione client](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication) della tua app. Gli esempi la leggono dal file indicato dalla variabile d’ambiente `CLIENT_ASSERTION_FILE` oppure dalla variabile di shell `CLIENT_ASSERTION`.

## Mantieni segreti i token OAuth

Conserva il token di accesso, il refresh token e i relativi tempi di scadenza di ogni cliente in un archivio di segreti che solo il servizio che esegue l’aggiornamento può leggere. Chiunque possieda un token di accesso può addebitare quel cliente fino alla scadenza del token. Se un token viene divulgato, prima [scollega il cliente](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/manage-customers#unlink-a-customer), poi collegalo di nuovo. Se perdi un refresh token, [collega di nuovo il cliente](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

## Chiama Claude con il token di accesso di un cliente

Invia il token di accesso del cliente al posto della credenziale del tuo account di servizio operatore:

* **Nell’Anthropic SDK:** Passa il token di accesso del cliente come token di autenticazione del client quando crei il client.
* **Nella CLI `ant`:** Imposta `ANTHROPIC_AUTH_TOKEN` sul token per il comando.
* **In una richiesta HTTP:** Invialo come bearer token nell’header `Authorization`. Non inviare un header `x-api-key`.

<Warning>
  Rimuovi `ANTHROPIC_API_KEY` ovunque usi il token di accesso di un cliente: alcuni client inviano invece la chiave, e Anthropic può addebitare a te.
</Warning>

Quei client sono la CLI `ant` e un client SDK che legge il token da `ANTHROPIC_AUTH_TOKEN`. Per il motivo e una protezione contro questo comportamento, consulta [Se una chiave API può raggiungere il processo](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-an-api-key-can-reach-the-process). Se la tua ricerca non trova alcun token per il cliente, fermati prima di creare il client. Con un token nullo, l’SDK potrebbe ripiegare sulla tua credenziale e addebitare a te.

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

Il token di accesso di un cliente funziona solo su questi endpoint:

* `/v1/messages` e `/v1/chat/completions`
* `/v1/messages/count_tokens`
* gli endpoint Models

Su `/v1/messages` e `/v1/chat/completions`, il solo token di accesso addebita il cliente. Non hai bisogno dell’header `anthropic-user-profile-id` né di [`billing_policy`](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request).

Invia ogni altra richiesta e ogni richiesta che paghi tu come tuo account di servizio operatore. Ciò include le richieste che usano l’esecuzione di codice a pagamento, che [non può essere addebitata a un cliente](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing#if-you-use-code-execution).

Le richieste con il token vengono eseguite nel workspace che hai impostato come predefinito per la tua app. Archiviarlo revoca tutti i token al suo interno: consulta [Se passi a un altro workspace](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace). Se una richiesta con il token viene rifiutata, consulta [Errori di Linked billing](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/errors).

## Aggiorna i token OAuth

Il token di accesso di un cliente dura al massimo 1 ora. Prima che scada, invia il refresh token del cliente all’endpoint dei token per ottenere una nuova coppia di token. Ogni refresh token funziona una sola volta, a parte un’unica ripetizione entro 30 secondi per recuperare una risposta che hai perso.

<Warning>
  Un refresh token inviato di nuovo più di 30 secondi dopo il suo primo utilizzo termina la connessione del cliente, e dovrai collegarlo di nuovo.
</Warning>

Per assicurarti di non inviare mai in ritardo un token già usato:

* Disattiva i tentativi automatici per la richiesta di aggiornamento nel tuo client HTTP e in qualsiasi proxy.
* Aggiorna i token OAuth di ogni cliente da un unico servizio, un aggiornamento alla volta per ciascun cliente. Se il servizio ha repliche, fornisci loro un lock condiviso. Mantienilo dalla lettura dei token memorizzati di un cliente fino a quando i nuovi non sono memorizzati.
* Memorizza il nuovo refresh token prima di usare il nuovo token di accesso.

La richiesta è una grant `refresh_token` verso `auth.claude.com`. Contiene il refresh token e l’[autenticazione client](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication) della tua app: `client_id` e una client assertion. Nessun SDK copre `auth.claude.com`, quindi gli esempi lo chiamano tramite HTTP. Mostrano la chiamata semplice, senza gestione degli errori:

<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">
    La CLI `ant` non ha alcun comando per `auth.claude.com`. Invia l’aggiornamento con cURL o nel linguaggio della tua applicazione.
  </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}");
      }

      // I nuovi access_token e 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}");
      }

      // I nuovi access_token e 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>

La risposta contiene un nuovo token di accesso e un nuovo refresh token. `expires_in` e `refresh_token_expires_in` indicano le loro durate in secondi. Il nuovo refresh token sostituisce quello che hai inviato, e il token di accesso precedente smette di funzionare entro pochi minuti.

Prima di inviare di nuovo un token dopo un aggiornamento non riuscito, leggi [cosa fare se un aggiornamento non riesce](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails). Alcuni nuovi tentativi terminano la connessione, e alcuni errori richiedono di mettere in pausa gli aggiornamenti di tutti i clienti. L’[esempio completo di aggiornamento](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#full-refresh-sample) gestisce questi errori.

Un refresh token dura al massimo 1 anno dallo scambio del codice, e un aggiornamento non estende questa durata. Prima che scada, [collega di nuovo il cliente](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

## Esegui un agente in una sandbox

Prima di usare questa sezione, leggi la sezione 4.1(b) dei [Linked Billing Beta Terms](https://www.anthropic.com/legal/linked-billing-terms). Se hai domande in merito, rivolgiti al tuo team account Anthropic.

Quando un agente lavora per un cliente in una sandbox, segui queste regole:

* Fornisci alla sandbox solo il token di accesso, mai il refresh token. Il tuo back end aggiorna i token e invia ogni nuovo token di accesso alla sandbox.
* Decidi quale cliente serve una sandbox in base all’identità della sandbox stessa, come la sua identità del pod. Non decidere mai in base a un valore inviato dalla sandbox.
* Invia a una sandbox solo il token del cliente che serve.
* Non fornire alla sandbox alcun token di identità montato né accesso a un server di metadati cloud.

Quest’ultima regola impedisce alla sandbox di ottenere un JWT che corrisponda all’autenticazione client della tua app o a una delle tue [regole di federazione](https://platform.claude.com/docs/it/manage-claude/workload-identity-federation). Con un JWT del genere, il codice nella sandbox potrebbe autenticarsi come la tua app o come uno dei tuoi account di servizio.

L’Anthropic SDK, Claude Code e il [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) possono leggere il token di accesso da un file di credenziali in un profilo di configurazione. Per il formato del file, consulta [File di configurazione del profilo](https://platform.claude.com/docs/it/manage-claude/wif-reference#profile-configuration-file). Per configurare la sandbox:

<Steps>
  <Step title="Aggiungi un profilo">
    Nella sandbox, crea una directory di configurazione. Al suo interno, aggiungi un profilo in `configs/customer.json` il cui tipo di autenticazione è `user_oauth`. Non assegnare al profilo un `client_id`: con esso, l’SDK si aspetta un refresh token nel file e aggiorna il token autonomamente.

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

  <Step title="Scrivi il token di accesso">
    Prima che l’agente si avvii, scrivi il token di accesso in `credentials/customer.json` nella stessa directory di configurazione, in modo che `configs` e `credentials` si trovino affiancate. Scrivilo di nuovo subito dopo ogni aggiornamento. `expires_at` è il tempo di scadenza del token in secondi Unix. Per il codice che lo scrive in modo sicuro, consulta [Quando scrivi ogni nuovo token di accesso in una sandbox](https://platform.claude.com/docs/it/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="Indirizza il client al profilo">
    Imposta `ANTHROPIC_CONFIG_DIR` sulla directory di configurazione e `ANTHROPIC_PROFILE` su `customer`.
  </Step>

  <Step title="Rimuovi ogni altra credenziale">
    Rimuovi ogni altra credenziale nella sandbox, perché ciascuna può avere la precedenza sul profilo. Tra queste:

    * le variabili d’ambiente `ANTHROPIC_API_KEY` e `ANTHROPIC_AUTH_TOKEN`
    * la variabile d’ambiente `CLAUDE_CODE_OAUTH_TOKEN` e l’impostazione `apiKeyHelper` di Claude Code
  </Step>
</Steps>

L’SDK rileva ogni nuovo token senza riavvio: consulta [Quando scrivi ogni nuovo token di accesso in una sandbox](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#when-you-write-each-new-token-to-a-sandbox).

## Verifica il risultato

Per confermare che una richiesta sia stata addebitata al cliente, consulta [dove appare una richiesta addebitata](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#check-the-result). Per confermare che un token sia limitato al suo cliente:

* Una richiesta con il token che indica un altro dei tuoi profili utente riceve `400 invalid_request_error`.
* Pochi minuti dopo un aggiornamento, una richiesta con il token di accesso precedente riceve `401 authentication_error`.

## Decidi se disattivare l’autenticazione solo operatore

Per impostazione predefinita, il tuo account di servizio operatore può addebitare qualsiasi cliente collegato senza il token di accesso del cliente. Indica il profilo utente del cliente e imposta `bill_to: "user_profile"` in [`billing_policy`](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request). Questa impostazione predefinita si chiama “operator-only authentication” (autenticazione solo operatore) e continua a funzionare anche dopo la scadenza del token di accesso di un cliente.

Una volta che le richieste di ogni cliente usano il proprio token di accesso, puoi disattivare l’autenticazione solo operatore. A quel punto, solo il token di accesso del cliente stesso può addebitarlo, quindi un bug che indica il profilo utente sbagliato non può addebitare il cliente sbagliato.

Le richieste di ogni cliente dipendono allora dagli aggiornamenti. Se perdi il refresh token di un cliente, non puoi addebitarlo finché non [si collega di nuovo](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again). Qualsiasi cosa interrompa gli aggiornamenti, come disattivare **Offline access** o rimuovere il [workspace predefinito](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#default-workspace), fa fallire le richieste di ogni cliente man mano che i loro token di accesso scadono.

La Claude Console verifica solo che la tua app abbia `billing:attribution`, `offline_access` e un workspace predefinito. Prima di disattivare l’autenticazione solo operatore, verifica tu stesso quanto segue:

* Il tuo archivio contiene un refresh token per ogni cliente collegato.
* Le tue richieste con i loro token di accesso funzionano.

Per disattivare l’autenticazione solo operatore:

1. Apri la scheda **Client authentication** dell’app nella Console.
2. Sotto l’account di servizio operatore, attiva **Disable operator-only tokenless authentication** e conferma nella finestra di dialogo. Il suo nome nell’API è `disable_operator_only_auth`.

Si applicano quindi queste regole:

* Una richiesta proveniente dal solo account di servizio che imposta `bill_to: "user_profile"` per un cliente collegato riceve `403 user_profile_not_billable`. Il cliente risulta ancora **Linked**, quindi monitora i tuoi log per questo errore.
* L’account di servizio può ancora gestire i profili utente e inviare le richieste che paghi tu.
* Per tornare all’impostazione predefinita, disattiva la stessa impostazione.

## Dettagli di implementazione, regole e casi particolari

Il resto di questa pagina contiene i dettagli alla base dei passaggi. Tratta gli aggiornamenti non riusciti, un esempio completo di aggiornamento e il modo in cui una chiave API o un aggiornamento influiscono su un client in esecuzione. Un cliente che ha approvato solo lo scope deprecato non ha un proprio token di accesso: consulta [Se usi ancora lo scope deprecato](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-still-use-the-deprecated-scope).

### Se un aggiornamento non riesce

Un aggiornamento sostituisce il refresh token che hai inviato. Cosa succede quando il token sostituito arriva di nuovo dipende da quando arriva:

* **Entro 30 secondi, la prima volta:** Restituisce una nuova coppia di token e revoca la coppia che non hai mai ricevuto. Questo ti consente di ripetere un aggiornamento la cui risposta è andata persa.
* **Entro 30 secondi, la prima volta, se il token che hai inviato aveva meno di 30 secondi quando è stato sostituito:** Riceve `invalid_grant`, e la connessione resta.
* **Entro 30 secondi, qualsiasi volta successiva:** Riceve `invalid_grant`, e la connessione resta.
* **Dopo 30 secondi:** Riceve `invalid_grant` e termina la connessione. Ogni token viene revocato, il cliente risulta **Unlinked** e nulla può addebitarlo finché non si collega di nuovo.

Dopo un aggiornamento non riuscito, cosa fare dipende dal fatto che il refresh token abbia raggiunto `auth.claude.com` e sia stato usato:

| Cosa ha ricevuto l’aggiornamento | Cosa significa | Cosa fare |
| ----- | ----- | ----- |
| La richiesta non ha potuto raggiungere `auth.claude.com`, incluso un timeout di connessione | Il token non è stato inviato | Invialo di nuovo più tardi |
| `429` | Nulla è stato revocato | Attendi, poi invialo di nuovo |
| Un rifiuto `503`: un header `retry-after` e `"type": "error"` al livello superiore del corpo | Nulla è stato revocato | Attendi, poi invialo di nuovo |
| Qualsiasi altro `4xx`, tranne `invalid_grant` | Nulla è stato revocato | Correggi la causa, poi invialo di nuovo |
| Qualsiasi altro `5xx` o un’interruzione di rete dopo l’invio della richiesta | Potrebbe aver funzionato | Invialo ancora una volta, subito |
| Nessuna risposta in tempo (un timeout di lettura) | Potrebbe essere ancora in esecuzione | Non inviarlo di nuovo |
| `invalid_grant` | Il token non può essere usato ora | Smetti di inviarlo |

**Attendi, poi invialo di nuovo:** Attendi almeno quanto indicato da `retry-after`. Se un `429` non ha l’header `retry-after`, applica un backoff prima di inviarlo di nuovo. Un `503` privo di uno dei due indicatori vale come qualsiasi altro `5xx`.

**Correggi la causa, poi invialo di nuovo:**

* `unauthorized_client`: `error_description` di solito indica la causa, come un workspace predefinito mancante o `offline_access` non più attivo sulla tua app.
* `invalid_client`: la tua client assertion non è valida. Verificala rispetto a [Claim della client assertion](https://platform.claude.com/docs/it/manage-claude/oauth-apps/endpoints-and-parameters#client-assertion-claims).
* `invalid_scope`: la richiesta ha inviato un parametro `scope`, oppure `billing:attribution` non è più attivo sulla tua app.
* Qualsiasi altro `4xx`, come `invalid_request`: correggi la richiesta.

Se hai modificato o archiviato l’account di servizio operatore, ogni aggiornamento di un token funzionante riceve `unauthorized_client`, e inviarlo di nuovo non può aiutare. Consulta [Se modifichi l’account di servizio](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-change-the-service-account).

**Invialo ancora una volta, subito:** `auth.claude.com` deve ricevere la seconda richiesta entro 30 secondi dalla sostituzione del token. Non puoi sapere quando è avvenuta, quindi conta dal momento in cui hai inviato la prima richiesta e lascia il tempo alla seconda di arrivare. Quindi:

* Se la seconda richiesta restituisce nuovi token, memorizzali e usa solo quelli.
* Se restituisce qualsiasi altra cosa, non riceve risposta o non può partire in tempo, non inviare di nuovo il token.

**Non inviarlo di nuovo:** Dopo un timeout di lettura o una risposta persa che non puoi recuperare, smetti di aggiornare i token di quel cliente e [collegalo di nuovo](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

**Smetti di inviarlo:** Smetti di aggiornare i token di quel cliente. `invalid_grant` di solito indica uno dei casi seguenti, e la risposta non specifica quale, quindi verifica i primi due prima di collegare di nuovo qualcuno:

* L’organizzazione del cliente è sospesa. Non scollegare il cliente e conserva il refresh token: funzionerà di nuovo al termine della sospensione. Per scoprirlo, chiedi al [supporto Anthropic](https://support.claude.com/en/articles/9015913-how-to-get-support) o al tuo team account Anthropic, se ne hai uno.
* L’aggiornamento di ogni cliente ha ricevuto `invalid_grant` nello stesso momento. Cerca una causa dal tuo lato, come un [workspace archiviato](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace).
* Il token è scaduto o era già stato usato, la connessione è terminata oppure il suo workspace è stato archiviato. [Collega di nuovo il cliente](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

Una connessione di rete persa, una risposta `5xx` o un timeout possono indicare un guasto di `auth.claude.com`. Se uno di questi ti ha fatto smettere di aggiornare i token di un cliente, evita che il guasto ti costi altre connessioni:

1. Metti in pausa gli aggiornamenti degli altri tuoi clienti.
2. Aggiorna i token di un cliente.
3. Riprendi gli altri solo dopo che quell’aggiornamento riesce o riceve una risposta `4xx`.

### Esempio completo di aggiornamento

Questa versione dell’aggiornamento segue [Se un aggiornamento non riesce](https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails). Aggiunge queste protezioni alla chiamata semplice:

* Aggiorna i token quando al token di accesso restano meno di 10 minuti.
* Mantiene un lock per ogni cliente dalla lettura dei token memorizzati fino alla memorizzazione dei nuovi.
* Prima che il refresh token lasci il processo, contrassegna i token memorizzati come `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`), in modo che un arresto anomalo non possa portare a un secondo invio.
* Attende fino a 2 secondi per raggiungere `auth.claude.com` e 10 secondi per una risposta.
* Invia una seconda richiesta solo entro 4 secondi dalla prima. Questo lascia il tempo alla seconda di arrivare entro i 30 secondi. Mantiene inoltre la seconda all’interno dell’attesa di 10 secondi, in modo che una richiesta scaduta per timeout non venga mai inviata di nuovo.
* Se fallisce solo la scrittura nel tuo archivio di segreti, ritenta la scrittura e non aggiorna di nuovo i token.

L’esempio lascia a te tre cose:

* un lock condiviso da tutte le tue repliche, perché il suo lock non raggiunge le altre repliche
* l’attesa e il nuovo invio dopo un `429` o un rifiuto `503`, che segnala come errore
* la messa in pausa degli aggiornamenti degli altri clienti dopo un aggiornamento perso, su ogni replica

Chiama la funzione di aggiornamento per ogni cliente più spesso di ogni 10 minuti, in modo che venga sempre eseguita all’interno di quel margine.

`refresh_connection()` (typescript, go, java, php: `refreshConnection()`; csharp: `Connections.RefreshConnection()`) fallisce con `RefreshOnHoldError` (csharp, java, php: `RefreshOnHoldException`) quando un refresh token non deve essere inviato di nuovo. Fallisce anche a ogni chiamata successiva per quel cliente. Il record memorizzato mantiene `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`) e `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`), così potrai sapere in seguito perché è stata impostata la messa in attesa. Quando è fallita solo la scrittura, il campo `new_tokens` (typescript, java, php: `newTokens`; csharp, go: `NewTokens`) dell’errore contiene i token da memorizzare.

La configurazione seguente definisce i nomi condivisi. Scrivi tu `load_tokens()` (typescript, go, java, php: `loadTokens()`; csharp: `LoadTokens()`) e `save_tokens()` (typescript, go, java, php: `saveTokens()`; csharp: `SaveTokens()`) per il tuo archivio di segreti.

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    Questa configurazione accompagna la funzione di aggiornamento che segue, che richiede più logica di un singolo comando shell. Scrivile entrambe nel linguaggio della tua applicazione.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Questa configurazione accompagna la funzione di aggiornamento che segue, che richiede più logica di un singolo comando shell. Scrivile entrambe nel linguaggio della tua applicazione.
  </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"
  )
  {
      // Tiene i token fuori dai log.
      public override string ToString() =>
          $"ConnectionTokens {{ ExpiresAt = {ExpiresAt}, OnHold = {OnHold}, HoldReason = {HoldReason} }}";
  }

  /// <summary>Il refresh token non deve essere inviato di nuovo. Non intercettare questa eccezione per riprovare.</summary>
  class RefreshOnHoldException(string message) : Exception(message)
  {
      /// <summary>Se impostato, è fallita solo la scrittura: memorizza questi token.</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>Legge il JWT che autentica la tua app presso auth.claude.com.</summary>
      static string ClientAssertion() =>
          File.ReadAllText(Environment.GetEnvironmentVariable("CLIENT_ASSERTION_FILE")!).Trim();

      /// <summary>Legge i token più recenti della connessione dal tuo archivio dei segreti.</summary>
      static Task<ConnectionTokens> LoadTokens(string connectionId) =>
          throw new NotImplementedException("Read the tokens from your secret store.");

      /// <summary>Scrive i token più recenti della connessione nel tuo archivio dei segreti.</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 tiene i token fuori dai log.
  func (t ConnectionTokens) String() string {
  	return fmt.Sprintf("ConnectionTokens{ExpiresAt: %d, OnHold: %t, HoldReason: %q}", t.ExpiresAt, t.OnHold, t.HoldReason)
  }

  // RefreshOnHoldError indica che il refresh token non deve essere inviato di nuovo. Non riprovare.
  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 legge il JWT che autentica la tua app presso auth.claude.com.
  func clientAssertion() (string, error) {
  	jwt, err := os.ReadFile(os.Getenv("CLIENT_ASSERTION_FILE"))
  	return strings.TrimSpace(string(jwt)), err
  }

  // loadTokens legge i token più recenti della connessione dal tuo archivio di segreti.
  func loadTokens(connectionID string) (ConnectionTokens, error) {
  	return ConnectionTokens{}, errors.New("read the tokens from your secret store")
  }

  // saveTokens scrive i token più recenti della connessione nel tuo archivio di segreti.
  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

    # Tiene i token fuori dai log.
    def inspect = "#<data ConnectionTokens expires_at=#{expires_at} on_hold=#{on_hold} hold_reason=#{hold_reason.inspect}>"
    alias_method :to_s, :inspect
  end

  # Il refresh token non deve essere inviato di nuovo. Non intercettare questo errore per riprovare.
  # Se new_tokens è impostato, è fallita solo la scrittura: memorizza quei token.
  class RefreshOnHoldError < StandardError
    attr_accessor :new_tokens
  end

  # Legge il JWT che autentica la tua app presso auth.claude.com.
  def client_assertion = File.read(ENV.fetch("CLIENT_ASSERTION_FILE")).strip

  # Legge i token più recenti della connessione dal tuo archivio di segreti.
  def load_tokens(connection_id)
    raise NotImplementedError, "Read the tokens from your secret store."
  end

  # Scrive i token più recenti della connessione nel tuo archivio di segreti.
  def save_tokens(connection_id, tokens)
    raise NotImplementedError, "Write the tokens to your secret store."
  end
  ```
</CodeGroup>

La seguente funzione di aggiornamento usa quella configurazione:

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    Questo aggiornamento richiede più logica di un singolo comando shell. Scrivilo nel linguaggio della tua applicazione.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Questo aggiornamento richiede più logica di un singolo comando shell. Scrivilo nel linguaggio della tua applicazione.
  </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.
      """
      # Questo lock funziona solo all'interno di un singolo processo.
      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(),
          }
          # Applica prima il blocco, così resta attivo se il processo si ferma durante il refresh.
          held = replace(tokens, on_hold=True, hold_reason="lost")
          save_tokens(connection_id, held)
          issued_at = int(time.time())
          started = time.monotonic()
          # Non aggiungere tentativi: un tentativo tardivo interrompe il collegamento del cliente.
          try:
              response = httpx2.post(TOKEN_URL, json=request, timeout=REQUEST_TIMEOUT)
              lost = is_lost(response)
          except (httpx2.ConnectError, httpx2.ConnectTimeout):
              # Il refresh token non è mai uscito da questo processo, quindi rimuovi il blocco.
              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:
              # Un rifiuto che conserva il refresh token, quindi rimuovi il blocco.
              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"],
          )
          # Ritenta solo la scrittura. Non eseguire di nuovo il refresh.
          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 } = {}) {
    // Questo lock funziona solo all'interno di un singolo processo.
    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()
      });
      // Acquisisci prima il blocco, così resta attivo se il processo si interrompe durante il refresh.
      const held: ConnectionTokens = { ...tokens, onHold: true, holdReason: "lost" };
      await saveTokens(connectionId, held);
      const issuedAt = Math.floor(Date.now() / 1000);
      const started = performance.now();
      // Non aggiungere tentativi: un tentativo tardivo interrompe il collegamento del cliente.
      let response: TokenResponse | undefined;
      try {
        response = await post(body);
      } catch (error) {
        if (error instanceof NotSent) {
          // Il refresh token non ha mai lasciato questo processo, quindi rimuovi il blocco.
          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) {
        // Un rifiuto che mantiene il refresh token, quindi rimuovi il blocco.
        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
      };
      // Ritenta solo la scrittura. Non eseguire di nuovo il refresh.
      for (let attempt = 0; attempt < 5; attempt++) {
        try {
          await saveTokens(connectionId, newTokens);
          return { accessToken: newTokens.accessToken, expiresAt: newTokens.expiresAt };
        } catch {
          // la scrittura non è riuscita
          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>True per una risposta 5xx che può seguire un refresh andato a buon fine.</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>
      /// Restituisce un token di accesso valido e la sua scadenza in secondi Unix.
      /// Chiamalo dalla tua pianificazione. Passa force: true per aggiornare un token non
      /// vicino alla scadenza. Lancia RefreshOnHoldException quando il refresh token non deve essere
      /// inviato di nuovo, e HttpRequestException per un rifiuto che lo mantiene valido.
      /// </summary>
      public static async Task<(string AccessToken, long ExpiresAt)> RefreshConnection(
          string connectionId, bool force = false)
      {
          // Questo lock funziona solo all'interno di un singolo processo.
          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(),
              });
              // Imposta prima il blocco, così resta attivo se il processo si ferma a metà refresh.
              var held = tokens with { OnHold = true, HoldReason = "lost" };
              await SaveTokens(connectionId, held);
              var issuedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
              var started = Stopwatch.StartNew();
              // Non aggiungere tentativi: un tentativo tardivo interrompe il collegamento del cliente.
              var (response, body, error, connected) = await Post(request);
              if (!connected)
              {
                  // Il refresh token non ha mai lasciato questo processo, quindi rimuovi il blocco.
                  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)
              {
                  // Un rifiuto che mantiene valido il refresh token, quindi rimuovi il blocco.
                  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());
              // Riprova solo la scrittura. Non eseguire un nuovo refresh.
              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 invia il refresh. connected è false se la richiesta non è mai partita.
  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 è true per una risposta 5xx che può seguire un refresh andato a buon fine.
  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 restituisce un token di accesso valido e la sua scadenza in secondi
  // Unix. Chiamala dalla tua pianificazione. Passa force=true per aggiornare un token
  // non vicino alla scadenza. Restituisce un *RefreshOnHoldError quando il refresh
  // token non deve essere reinviato, e un altro errore per un rifiuto che lo mantiene valido.
  func refreshConnection(connectionID string, force bool) (string, int64, error) {
  	// Questo lock funziona solo all'interno di un singolo processo.
  	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
  	}
  	// Imposta prima il blocco, così resta se il processo si ferma durante il refresh.
  	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()
  	// Non aggiungere tentativi: un tentativo tardivo interrompe il collegamento del cliente.
  	response, connected, err := post(body)
  	if err != nil && !connected {
  		// Il refresh token non è mai uscito da questo processo, quindi rimuovi il blocco.
  		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 {
  		// Un rifiuto che mantiene valido il refresh token, quindi rimuovi il blocco.
  		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,
  	}
  	// Riprova solo la scrittura. Non eseguire di nuovo il refresh.
  	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 {
      // Questo lock funziona solo all'interno di un singolo processo.
      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();
          // Applica prima il blocco, così resta attivo se il processo si interrompe durante il refresh.
          var held = tokens.withHold("lost");
          saveTokens(connectionId, held);
          long issuedAt = Instant.now().getEpochSecond();
          long started = System.nanoTime();
          // Non aggiungere tentativi: un tentativo tardivo interrompe il collegamento del cliente.
          HttpResponse<String> response = null;
          try {
              response = post(request);
          } catch (ConnectException | HttpConnectTimeoutException | SSLHandshakeException e) {
              // Il refresh token non ha mai lasciato questo processo, quindi rimuovi il blocco.
              saveTokens(connectionId, tokens);
              throw e;
          } catch (IOException _) {
              // La connessione è caduta o non è arrivata risposta in tempo.
          }
          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) {
              // Un rifiuto che mantiene il refresh token, quindi rimuovi il blocco.
              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);
          // Ritenta solo la scrittura. Non eseguire di nuovo il refresh.
          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)) {
          // Nessuna connessione TLS ancora significa che non è stato inviato nulla.
          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
  {
      // Questo lock funziona solo su una singola macchina.
      $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);
          // Imposta prima il blocco, così resta attivo se il processo si arresta a metà refresh.
          $held = $tokens->withHold('lost');
          saveTokens($connectionId, $held);
          $issuedAt = time();
          $started = hrtime(true);
          // Non aggiungere tentativi: un tentativo tardivo interrompe il collegamento del cliente.
          $response = post($request);
          if (is_string($response)) {
              // Il refresh token non ha mai lasciato questo processo, quindi rimuovi il blocco.
              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) {
              // Un rifiuto che mantiene il refresh token, quindi rimuovi il blocco.
              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'],
          );
          // Ritenta solo la scrittura. Non eseguire di nuovo il refresh.
          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

  # Solleva un'eccezione prima che la richiesta parta se non riesce a connettersi.
  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

  # True per una risposta 5xx che può seguire un refresh andato a buon fine.
  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

  # Restituisce un token di accesso valido e la sua scadenza in secondi Unix.
  #
  # Chiamalo dalla tua pianificazione. Passa force: true per aggiornare un token non
  # vicino alla scadenza. Solleva RefreshOnHoldError quando il refresh token non deve essere
  # inviato di nuovo, e RuntimeError per un rifiuto che lo mantiene valido.
  def refresh_connection(connection_id, force: false)
    # Questo lock funziona solo all'interno di un singolo processo.
    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
      # Imposta prima il blocco, così resta attivo se il processo si ferma a metà refresh.
      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)
      # Non aggiungere tentativi: un tentativo tardivo interrompe il collegamento del cliente.
      begin
        http = open_connection
      rescue
        # Il refresh token non ha mai lasciato questo processo, quindi rimuovi il blocco.
        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"
        # Un rifiuto che mantiene valido il refresh token, quindi rimuovi il blocco.
        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")
      )
      # Riprova solo la scrittura. Non eseguire di nuovo il refresh.
      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>

### Se una chiave API può raggiungere il processo

Questa sezione riguarda solo un processo in cui `ANTHROPIC_API_KEY` potrebbe essere impostata accanto al token di accesso di un cliente. Questi client inviano la chiave al posto del token:

* la CLI `ant`
* un client SDK che legge il token da `ANTHROPIC_AUTH_TOKEN`

Un client SDK a cui viene fornito il token al momento della creazione invia solo il token. Altri client possono inviarli entrambi. La chiave ha comunque la precedenza, tranne sugli endpoint Models, dove la richiesta può essere rifiutata. Quando viene inviata la chiave, la Claude API autentica la richiesta con essa, quindi la richiesta non è limitata a quel cliente.

Come protezione in un processo di questo tipo, invia ogni richiesta con l’header `anthropic-user-profile-id`, `billing_policy` con `bill_to: "user_profile"` e l’header beta `user-profiles-billing-2026-10-01`. A quel punto, una richiesta inviata con la chiave ha uno di questi esiti:

* **Con l’header e `bill_to: "user_profile"`:** Fallisce, oppure addebita il cliente indicato dall’header.
* **Con il solo header, o con nessuno dei due:** Anthropic la addebita a te.

### Quando scrivi ogni nuovo token di accesso in una sandbox

Il tuo back end invia ogni nuovo token al codice nella sandbox, tramite un canale che costruisci tu. Quel codice viene eseguito come utente dell’agente e scrive il token in una directory `credentials` con modalità `0700`. Scrive un nuovo file con modalità `0600` e lo rinomina sovrascrivendo quello vecchio, in modo che l’agente non legga mai un file a metà. Questa funzione fa proprio questo:

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    Scrivi il file con il codice della tua applicazione, eseguito nella sandbox come utente dell’agente.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Scrivi il file con il codice della tua applicazione, eseguito nella sandbox come utente dell’agente.
  </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>Esegui questo nella sandbox, come utente dell'agente.</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 viene eseguito nella sandbox, come utente dell'agente.
  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"

  # Esegui questo nella sandbox, come utente dell'agente.
  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>

Entro pochi minuti da un aggiornamento, una richiesta con il token precedente riceve un `401`. Il client può quindi rileggere il file e inviare la richiesta con il nuovo token. Con l’SDK TypeScript o C# da solo, quella singola richiesta fallisce invece. Inviala ancora una volta: la richiesta successiva usa il nuovo token. L’SDK rilegge inoltre il file negli ultimi 2 minuti prima di `expires_at`, oppure negli ultimi 30 secondi in Java.

### Per gli agenti

* Quando aggiorni i token, non inviare un parametro `scope`.
* A ogni aggiornamento, rileggi la client assertion dal suo file.
* Quando memorizzi nuovi token, calcola i loro tempi di scadenza a partire dal momento in cui hai inviato l’aggiornamento, usando `expires_in` e `refresh_token_expires_in`.
* Al termine di una sospensione, rimuovi `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`) solo se il relativo `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`) è `invalid_grant`.
* Quando scrivi il file delle credenziali di una sandbox, scrivi un token a cui restano più di 30 secondi prima del suo `expires_at`.

## Passaggi successivi

<CardGroup cols={2}>
  <Card title="Testa e pubblica la tua app" icon="rocket" href="https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/test-and-publish">
    Aggiungi utenti di test, pubblica la tua app e modificala o eliminala
  </Card>

  <Card title="Cosa vedono i tuoi clienti" icon="browser" href="https://platform.claude.com/docs/it/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    La pagina di approvazione, i tetti di spesa e le email che vedono i tuoi clienti, così puoi fornire loro supporto
  </Card>
</CardGroup>
