# Authentification serveur à serveur

Utilisez un jeton d'accès d'installation de courte durée lorsqu'un service doit effectuer des demandes Copilot pour le compte d'une organisation sans informations d'identification d'un utilisateur. Dans GitHub Actions, utilisez plutôt le composant GITHUB_TOKEN intégré.

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

## GitHub Actions

Pour les workflows d’un référentiel appartenant à l’organisation, accordez au jeton intégré l’autorisation d’effectuer des requêtes à Copilot :

```yaml
permissions:
  contents: read
  copilot-requests: write

jobs:
  copilot:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - run: your-application
        env:
          GITHUB_TOKEN: $
```

La stratégie de l’organisation **Autoriser l’utilisation de Copilot CLI facturée à l’organisation** doit être activée. Cette approche n’a pas besoin d’une application GitHub ou d’un secret d’authentification stocké. Pour plus d’informations, consultez [Utilisation de l’interface CLI Copilot dans GitHub Actions avec GITHUB\_TOKEN](/fr/copilot/how-tos/copilot-cli/use-copilot-cli-in-actions).

## Autres services et systèmes CI

Pour les services en dehors de GitHub Actions :

1. Créez une application GitHub avec l’autorisation de dépôt **Requêtes Copilot** définie sur **Lecture et écriture**.

2. Installez-le sur l’organisation qui doit être facturée. La vérification des autorisations Copilot actuelle nécessite **l’accès à tous les référentiels**.

3. [Génération d’un jeton d’accès d’installation pour une application GitHub](/fr/apps/creating-github-apps/authenticating-with-a-github-app/generating-an-installation-access-token-for-a-github-app) avec un ID de référentiel et l’autorisation Copilot :

   ```json
   {
     "repository_ids": [123456789],
     "permissions": {
       "copilot_requests": "write"
     }
   }
   ```

4. Transmettez le jeton résultant `ghs_` au runtime en tant que `COPILOT_GITHUB_TOKEN`.

L’organisation doit être activée pour les requêtes Copilot provenant des installations de GitHub App. Les jetons d’installation expirent après une heure.

> \[!WARNING]
> Ne transmettez pas de jeton d’installation via l’option `gitHubToken`, `github_token` ou une option équivalente du SDK. Cette option concerne les jetons utilisateur. Les jetons d’installation doivent utiliser le chemin d’authentification de l’environnement d’exécution.

## Configurer le runtime

Les exemples suivants supposent que le jeton créé se trouve dans `INSTALLATION_TOKEN`. Ils le transmettent uniquement à l’environnement d’exécution enfant et désactivent le recours aux informations d’identification utilisateur stockées.

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
import { CopilotClient, RuntimeConnection } from "@github/copilot-sdk";

const token = process.env.INSTALLATION_TOKEN;
if (!token) throw new Error("INSTALLATION_TOKEN is required");

const client = new CopilotClient({
    connection: RuntimeConnection.forStdio(),
    env: {
        ...process.env,
        COPILOT_GITHUB_TOKEN: token,
    },
    useLoggedInUser: false,
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
import os

from copilot import CopilotClient, RuntimeConnection

client = CopilotClient(
    connection=RuntimeConnection.for_stdio(),
    env={**os.environ, "COPILOT_GITHUB_TOKEN": os.environ["INSTALLATION_TOKEN"]},
    use_logged_in_user=False,
)
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
package main

import (
    "log"
    "os"

    copilot "github.com/github/copilot-sdk/go"
)

func main() {
    token, ok := os.LookupEnv("INSTALLATION_TOKEN")
    if !ok {
        log.Fatal("INSTALLATION_TOKEN is required")
    }
    client := copilot.NewClient(&copilot.ClientOptions{
        Connection:      copilot.StdioConnection{},
        Env:             append(os.Environ(), "COPILOT_GITHUB_TOKEN="+token),
        UseLoggedInUser: copilot.Bool(false),
    })
    _ = client
}
```

</div>

<div class="ghd-codetab" data-lang="rust" data-label="Rust"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Rust</div>

```rust
use github_copilot_sdk::{ClientOptions, Transport};

fn main() {
    let token = std::env::var("INSTALLATION_TOKEN").expect("INSTALLATION_TOKEN is required");
    let options = ClientOptions::new()
        .with_transport(Transport::Stdio)
        .with_env([("COPILOT_GITHUB_TOKEN", token)])
        .with_use_logged_in_user(false);
    drop(options);
}
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
using System.Collections;
using GitHub.Copilot;

var token = Environment.GetEnvironmentVariable("INSTALLATION_TOKEN")
    ?? throw new InvalidOperationException("INSTALLATION_TOKEN is required");
var environment = Environment.GetEnvironmentVariables()
    .Cast<DictionaryEntry>()
    .ToDictionary(entry => (string)entry.Key, entry => entry.Value?.ToString() ?? "");
environment["COPILOT_GITHUB_TOKEN"] = token;

await using var client = new CopilotClient(new CopilotClientOptions
{
    Connection = RuntimeConnection.ForStdio(),
    Environment = environment,
    UseLoggedInUser = false,
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

```java
import com.github.copilot.CopilotClient;
import com.github.copilot.rpc.CopilotClientOptions;
import java.util.HashMap;
import java.util.Objects;

var environment = new HashMap<>(System.getenv());
var token = Objects.requireNonNull(
    System.getenv("INSTALLATION_TOKEN"), "INSTALLATION_TOKEN is required");
environment.put("COPILOT_GITHUB_TOKEN", token);

try (var client = new CopilotClient(new CopilotClientOptions()
        .setEnvironment(environment)
        .setUseLoggedInUser(false))) {
    // Use the client.
}
```

</div>

</div>

Pour la FFI dans le processus, définissez `COPILOT_GITHUB_TOKEN` dans l’environnement hôte avant de charger l’environnement d’exécution ; les options d’environnement propres à chaque client ne sont pas prises en charge. Pour un URI d’exécution existant, définissez-le sur ce processus d’exécution.

## Jetons d’actualisation

Générez un nouveau jeton d'installation avant que le jeton actuel n'expire. Pour un processus enfant, redémarrez le client SDK dans le nouvel environnement. Pour un runtime in-process ou existant, redémarrez le runtime hôte avec le nouveau jeton.

## Billing

L’utilisation est attribuée et facturée au compte propriétaire de l’installation de l’application GitHub. Utilisez une installation pour une organisation pour la facturation de l’organisation ; une installation pour un compte utilisateur attribue l’utilisation à cet utilisateur.

## Résolution des problèmes

| Symptôme                                                                                            | Vérifier                                                                                                                                               |
| --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `401 Unauthorized`                                                                                  | Vérifiez que l’organisation prend en charge l’authentification d’installation de l’application GitHub pour Copilot.                                    |
| `403 Resource not accessible by integration` ou une erreur mentionnant les informations utilisateur | Vérifiez que le jeton d’installation se trouve dans `COPILOT_GITHUB_TOKEN`, et non l’option de jeton explicite du Kit de développement logiciel (SDK). |
| `403 Forbidden`à partir de l’API Copilot                                                            | Vérifiez que la demande de jeton contient `repository_ids` et `copilot_requests: write`.                                                               |
| `403 Forbidden` avec la demande de jeton requise                                                    | Vérifiez que l’installation de l’application a accès à **Tous les dépôts**, puis générez un nouveau jeton.                                             |
| Le modèle demandé n’est pas disponible                                                              | Vérifiez que la stratégie de Copilot de l'organisation autorise le modèle et le runtime groupé le prend en charge.                                     |
| Compte incorrect facturé                                                                            | Vérifiez que l’installation appartient à l’organisation prévue.                                                                                        |

## Lectures complémentaires

* [Authentification](/fr/copilot/how-tos/copilot-sdk/auth/authenticate) : autres méthodes d’authentification et priorité
* [Génération d’un jeton d’accès d’installation pour une application GitHub](/fr/apps/creating-github-apps/authenticating-with-a-github-app/generating-an-installation-access-token-for-a-github-app) : création de jetons d’application GitHub