# 支持 BYOK（自带密钥）的 Azure 托管标识

GitHub Copilot SDK 的 BYOK （自带密钥） 支持静态 API 密钥，但Azure部署通常使用托管标识（Microsoft Entra ID），而不是长期密钥。 GitHub Copilot SDK 旨在使用Azure标识 SDK 进行组合，以实现最大的灵活性。 提供一个 Bearer 令牌提供程序回调，以便使用 Azure 标识 SDK API 在需要时获取新的令牌。

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

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

本指南介绍如何通过 GitHub Copilot SDK 使用 Azure Identity SDK API 对 Microsoft Foundry 模型进行身份验证。 大多数语言使用 `DefaultAzureCredential`；Rust 在本地使用 `DeveloperToolsCredential`，在 Azure 中使用 `ManagedIdentityCredential`。

## 工作原理

Microsoft Foundry 的 OpenAI 兼容终结点 （`https://<resource-name>.openai.azure.com/openai/v1/`） 接受来自Microsoft Entra ID的持有者令牌，以代替静态 API 密钥。 本指南使用令牌提供程序回调，以便GitHub Copilot SDK 运行时可以按需请求新的令牌。

以Python为例，流为：

1. 为环境配置 `DefaultAzureCredential` 。
2. 在 BYOK 提供程序配置的 `bearer_token_provider` 中传递一个回调函数，该函数使用 `DefaultAzureCredential` 获取用于 `https://ai.azure.com/.default` 范围的令牌。
3. 让GitHub Copilot SDK 通过该回调按需请求新令牌。

![关系图：显示描述的过程的序列图。](/assets/images/help/copilot/copilot-sdk/setup-azure-managed-identity-diagram-0.png)

## 代码示例

### 先决条件

为你所用的编程语言安装 Azure Identity 和 GitHub Copilot SDK 包：

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

<!-- docs-validate: skip -->

```bash
dotnet add package GitHub.Copilot.SDK
dotnet add package Azure.Core
```

</div>

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

<!-- docs-validate: skip -->

```bash
go get github.com/github/copilot-sdk/go
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
```

</div>

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

<!-- docs-validate: skip -->

```xml
<dependency>
    <groupId>com.github</groupId>
    <artifactId>copilot-sdk-java</artifactId>
    <version>${copilot.sdk.version}</version>
</dependency>

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>${azure.identity.version}</version>
</dependency>
```

</div>

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

<!-- docs-validate: skip -->

```bash
pip install github-copilot-sdk azure-identity
```

</div>

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

<!-- docs-validate: skip -->

```bash
cargo add github-copilot-sdk azure_identity azure_core
cargo add tokio --features macros,rt-multi-thread
```

</div>

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

<!-- docs-validate: skip -->

```bash
npm install @github/copilot-sdk @azure/identity
```

</div>

</div>

### 使用令牌提供方回调

如果希望 GitHub Copilot SDK 运行时通过提供的回调按需请求新令牌，请使用此方法。 Azure 标识 SDK 负责令牌缓存和刷新时机。

下面是特定语言的实现：

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

<!-- docs-validate: skip -->

```csharp
using Azure.Core;
using Azure.Identity;
using GitHub.Copilot;

DefaultAzureCredential credential = new(
    DefaultAzureCredential.DefaultEnvironmentVariableName);
await using CopilotClient client = new();
string foundryUrl = Environment.GetEnvironmentVariable("FOUNDRY_RESOURCE_URL")!;

await using CopilotSession session = await client.CreateSessionAsync(new SessionConfig
{
    Model = "gpt-5.5",
    Provider = new ProviderConfig
    {
        Type = "openai",
        BaseUrl = $"{foundryUrl}/openai/v1/",
        BearerTokenProvider = async _ =>
        {
            AccessToken token = await credential.GetTokenAsync(
                new TokenRequestContext(["https://ai.azure.com/.default"]));
            return token.Token;
        },
        WireApi = "responses",
    },
});

AssistantMessageEvent? response = await session.SendAndWaitAsync(
    new MessageOptions { Prompt = "Hello from Managed Identity!" });
Console.WriteLine(response?.Data.Content);
```

</div>

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

<!-- docs-validate: skip -->

```golang
package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "time"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    copilot "github.com/github/copilot-sdk/go"
)
func main() {
    opts := azidentity.DefaultAzureCredentialOptions{RequireAzureTokenCredentials: true}
    credential, err := azidentity.NewDefaultAzureCredential(&opts)
    if err != nil {
        log.Fatal(err)
    }

    getBearerToken := func(args copilot.ProviderTokenArgs) (string, error) {
        token, err := credential.GetToken(context.Background(), policy.TokenRequestOptions{
            Scopes: []string{"https://ai.azure.com/.default"},
        })
        if err != nil {
            return "", err
        }
        return token.Token, nil
    }

    client := copilot.NewClient(nil)
    if err := client.Start(context.Background()); err != nil {
        log.Fatal(err)
    }
    defer client.Stop()

    foundryURL := os.Getenv("FOUNDRY_RESOURCE_URL")

    session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
        Model: "gpt-5.5",
        Provider: &copilot.ProviderConfig{
            Type:                "openai",
            BaseURL:             fmt.Sprintf("%s/openai/v1/", foundryURL),
            BearerTokenProvider: getBearerToken,
            WireAPI:             "responses",
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    defer session.Disconnect()

    ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
    defer cancel()

    response, err := session.SendAndWait(ctx, copilot.MessageOptions{
        Prompt: "Hello from Managed Identity!",
    })
    if err != nil {
        log.Fatal(err)
    }

    if response != nil {
        if data, ok := response.Data.(*copilot.AssistantMessageData); ok {
            fmt.Println(data.Content)
        }
    }
}
```

</div>

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

<!-- docs-validate: skip -->

```java
import com.azure.core.credential.TokenRequestContext;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.github.copilot.CopilotClient;
import com.github.copilot.generated.AssistantMessageEvent;
import com.github.copilot.rpc.BearerTokenProvider;
import com.github.copilot.rpc.MessageOptions;
import com.github.copilot.rpc.ProviderConfig;
import com.github.copilot.rpc.SessionConfig;

public class ManagedIdentityExample {
    public static void main(String[] args) throws Exception {
        var credential = new DefaultAzureCredentialBuilder()
                .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
                .build();
        BearerTokenProvider tokenProvider = providerArgs ->
            credential
                .getToken(new TokenRequestContext().addScopes("https://ai.azure.com/.default"))
                .map(accessToken -> accessToken.getToken())
                .toFuture();
        String foundryUrl = System.getenv("FOUNDRY_RESOURCE_URL");

        try (var client = new CopilotClient()) {
            client.start().get();

            var session = client.createSession(new SessionConfig()
                    .setModel("gpt-5.5")
                    .setProvider(new ProviderConfig()
                            .setType("openai")
                            .setBaseUrl(foundryUrl + "/openai/v1/")
                            .setBearerTokenProvider(tokenProvider)
                            .setWireApi("responses")))
                .get();

            AssistantMessageEvent response = session
                    .sendAndWait(new MessageOptions().setPrompt("Hello from Managed Identity!"))
                    .get();
            System.out.println(response.getData().content());

            session.disconnect().get();
        }
    }
}
```

</div>

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

<!-- docs-validate: skip -->

```python
import asyncio
import os

from azure.identity.aio import DefaultAzureCredential
from copilot import CopilotClient
from copilot.session import PermissionHandler, ProviderConfig

async def main():
    credential = DefaultAzureCredential(require_envvar=True)
    async def get_bearer_token(_args) -> str:
        token = await credential.get_token("https://ai.azure.com/.default")
        return token.token

    foundry_url = os.environ["FOUNDRY_RESOURCE_URL"]

    client = CopilotClient()
    await client.start()

    session = await client.create_session(
        on_permission_request=PermissionHandler.approve_all,
        model="gpt-5.5",
        provider=ProviderConfig(
            type="openai",
            base_url=f"{foundry_url.rstrip('/')}/openai/v1/",
            bearer_token_provider=get_bearer_token,
            wire_api="responses",
        ),
    )

    response = await session.send_and_wait("Hello from Managed Identity!")
    print(response.data.content)

    await client.stop()
    await credential.close()

asyncio.run(main())
```

</div>

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

<!-- docs-validate: skip -->

```rust
use std::sync::Arc;

use azure_core::credentials::TokenCredential;
use azure_identity::{DeveloperToolsCredential, ManagedIdentityCredential};
use github_copilot_sdk::{BearerTokenError, Client, ClientOptions, MessageOptions, ProviderTokenArgs};
use github_copilot_sdk::types::{ProviderConfig, SessionConfig};

fn credential_for_environment() -> azure_core::Result<Arc<dyn TokenCredential>> {
    match std::env::var("AZURE_TOKEN_CREDENTIALS").as_deref() {
        Ok("ManagedIdentityCredential") => Ok(ManagedIdentityCredential::new(None)?),
        _ => Ok(DeveloperToolsCredential::new(None)?),
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let credential = credential_for_environment()?;
    let foundry_url = std::env::var("FOUNDRY_RESOURCE_URL")?;

    let get_bearer_token = {
        let credential = credential.clone();
        move |_args: ProviderTokenArgs| {
            let credential = credential.clone();
            async move {
                let token = credential
                    .get_token(&["https://ai.azure.com/.default"], None)
                    .await
                    .map_err(|err| BearerTokenError::message(err.to_string()))?;
                Ok(token.token.secret().to_string())
            }
        }
    };

    let mut provider = ProviderConfig::default();
    provider.provider_type = Some("openai".to_string());
    provider.base_url = format!("{}/openai/v1/", foundry_url.trim_end_matches('/'));
    provider.bearer_token_provider = Some(Arc::new(get_bearer_token));
    provider.wire_api = Some("responses".to_string());

    let mut config = SessionConfig::default();
    config.model = Some("gpt-5.5".to_string());
    config.provider = Some(provider);

    let client = Client::start(ClientOptions::default()).await?;
    let session = client.create_session(config).await?;

    session
        .send_and_wait(MessageOptions::new("Hello from Managed Identity!"))
        .await?;

    session.disconnect().await?;
    client.stop().await?;
    Ok(())
}
```

</div>

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

<!-- docs-validate: skip -->

```typescript
import { DefaultAzureCredential } from "@azure/identity";
import { CopilotClient } from "@github/copilot-sdk";

const credential = new DefaultAzureCredential({
  requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"],
});
const getBearerToken = async () => {
  const tokenResponse = await credential.getToken("https://ai.azure.com/.default");
  return tokenResponse.token;
};

const client = new CopilotClient();

const session = await client.createSession({
  model: "gpt-5.5",
  provider: {
    type: "openai",
    baseUrl: `${process.env.FOUNDRY_RESOURCE_URL}/openai/v1/`,
    bearerTokenProvider: getBearerToken,
    wireApi: "responses",
  },
});

const response = await session.sendAndWait({ prompt: "Hello from Managed Identity!" });
console.log(response?.data.content);

await client.stop();
```

</div>

</div>

## 环境配置

| Variable                                                                                                | Description                                         | 示例                                       |
| ------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ---------------------------------------- |
| `AZURE_TOKEN_CREDENTIALS`                                                                               | 在 **Azure** 中运行时，将其设置为 `ManagedIdentityCredential`. |                                          |
| **在本地**运行时，将其设置为 `dev` 或开发人员工具凭据名称，例如 `AzureCliCredential`。                                             | `ManagedIdentityCredential`                         |                                          |
| `AZURE_CLIENT_ID`                                                                                       |                                                     |                                          |
| *可选。* 在**Azure**中运行时，使用`ManagedIdentityCredential`时，将此 ID 设置为用户分配的托管标识的客户端 ID。 如果未设置，Azure将使用系统分配的托管标识。 | `11111111-2222-3333-4444-555555555555`              |                                          |
| `FOUNDRY_RESOURCE_URL`                                                                                  | 你的 Microsoft Foundry 资源 URL                         | `https://<my-resource>.openai.azure.com` |

不需要 API 密钥环境变量 - 身份验证由Azure标识凭据处理。 在 .NET 中，Go、Java、Python 和 TypeScript `DefaultAzureCredential` 会自动支持：

* **托管标识**（系统分配或用户分配）：适用于Azure托管的应用
* **Azure CLI** （`az login`）：用于本地开发
* **环境变量**（`AZURE_CLIENT_ID`、`AZURE_TENANT_ID`、`AZURE_CLIENT_SECRET`）：用于服务主体
* **工作负荷标识**：适用于 Kubernetes

在 .NET、Go、Java、Python 和 TypeScript 中，`ManagedIdentityCredential`读取`AZURE_CLIENT_ID`以选择用户分配的托管标识。 Rust 是本指南中的一个例外。

在 Rust 中，使用 `DeveloperToolsCredential` 进行本地开发，在 Azure 中运行时使用 `ManagedIdentityCredential`。 对于其他语言，请参阅 `DefaultAzureCredential` 文档以了解完整的凭据链：

* [.NET](https://aka.ms/azsdk/net/identity/credential-chains#defaultazurecredential-overview)
* [Go](https://aka.ms/azsdk/go/identity/credential-chains#defaultazurecredential-overview)
* [Java](https://aka.ms/azsdk/java/identity/credential-chains#defaultazurecredential-overview)
* [Python](https://aka.ms/azsdk/python/identity/credential-chains#defaultazurecredential-overview)
* [TypeScript](https://aka.ms/azsdk/js/identity/credential-chains#defaultazurecredential-overview)

## 何时使用此模式

| 情景                             | Recommendation                                                           |
| ------------------------------ | ------------------------------------------------------------------------ |
| 带有托管标识的 Azure 托管应用             |                                                                          |
| ✅ 使用此模式                        |                                                                          |
| 使用现有 Microsoft Entra 服务主体的应用程序 |                                                                          |
| ✅ 使用此模式                        |                                                                          |
| 使用 `az login` 进行本地开发           |                                                                          |
| ✅ 使用此模式                        |                                                                          |
| 具有静态 API 密钥的非 Azure 环境         | 使用 [BYOK （自带密钥）](/zh/copilot/how-tos/copilot-sdk/auth/byok)              |
| GitHub Copilot订阅可用             | 使用 [GitHub OAuth 设置](/zh/copilot/how-tos/copilot-sdk/setup/github-oauth) |

## 另见

* [BYOK （自带密钥）](/zh/copilot/how-tos/copilot-sdk/auth/byok)：静态 API 密钥配置
* [后端服务设置](/zh/copilot/how-tos/copilot-sdk/setup/backend-services)：服务器端部署