{"meta":{"title":"Azure managed identity with BYOK","intro":"The GitHub Copilot SDK's BYOK (bring your own key) supports static API keys, but Azure deployments often use Managed Identity (Microsoft Entra ID) instead of long-lived keys. The GitHub Copilot SDK is designed to compose with the Azure Identity SDK for maximum flexibility. Supply a bearer token provider callback that can fetch fresh tokens on demand using an Azure Identity SDK API.","product":"GitHub Copilot","breadcrumbs":[{"href":"/en/copilot","title":"GitHub Copilot"},{"href":"/en/copilot/how-tos","title":"How-tos"},{"href":"/en/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/en/copilot/how-tos/copilot-sdk/setup","title":"Set up Copilot SDK"},{"href":"/en/copilot/how-tos/copilot-sdk/setup/azure-managed-identity","title":"Azure Managed Identity"}],"documentType":"article"},"body":"# Azure managed identity with BYOK\n\nThe GitHub Copilot SDK's BYOK (bring your own key) supports static API keys, but Azure deployments often use Managed Identity (Microsoft Entra ID) instead of long-lived keys. The GitHub Copilot SDK is designed to compose with the Azure Identity SDK for maximum flexibility. Supply a bearer token provider callback that can fetch fresh tokens on demand using an Azure Identity SDK API.\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\nThis guide shows how to use Azure Identity SDK APIs to authenticate with Microsoft Foundry models through the GitHub Copilot SDK. Most languages use `DefaultAzureCredential`; Rust uses `DeveloperToolsCredential` locally and `ManagedIdentityCredential` in Azure.\n\n## How it works\n\nMicrosoft Foundry's OpenAI-compatible endpoint (`https://<resource-name>.openai.azure.com/openai/v1/`) accepts bearer tokens from Microsoft Entra ID in place of static API keys. This guide uses a token provider callback so the GitHub Copilot SDK runtime can request fresh tokens on demand.\n\nUsing Python as an example, the flow is:\n\n1. Configure `DefaultAzureCredential` for your environment.\n2. Pass a callback, in `bearer_token_provider` of the BYOK provider configuration, that uses `DefaultAzureCredential` to obtain a token for the `https://ai.azure.com/.default` scope.\n3. Let the GitHub Copilot SDK request fresh tokens on demand through that callback.\n\n![Diagram: Sequence diagram showing the described process.](/assets/images/help/copilot/copilot-sdk/setup-azure-managed-identity-diagram-0.png)\n\n## Code samples\n\n### Prerequisites\n\nInstall the Azure Identity and GitHub Copilot SDK packages for your language:\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n<!-- docs-validate: skip -->\n\n```bash\ndotnet add package GitHub.Copilot.SDK\ndotnet add package Azure.Core\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n<!-- docs-validate: skip -->\n\n```bash\ngo get github.com/github/copilot-sdk/go\ngo get github.com/Azure/azure-sdk-for-go/sdk/azidentity\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```xml\n<dependency>\n    <groupId>com.github</groupId>\n    <artifactId>copilot-sdk-java</artifactId>\n    <version>${copilot.sdk.version}</version>\n</dependency>\n\n<dependency>\n    <groupId>com.azure</groupId>\n    <artifactId>azure-identity</artifactId>\n    <version>${azure.identity.version}</version>\n</dependency>\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n<!-- docs-validate: skip -->\n\n```bash\npip install github-copilot-sdk azure-identity\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n<!-- docs-validate: skip -->\n\n```bash\ncargo add github-copilot-sdk azure_identity azure_core\ncargo add tokio --features macros,rt-multi-thread\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n<!-- docs-validate: skip -->\n\n```bash\nnpm install @github/copilot-sdk @azure/identity\n```\n\n</div>\n\n</div>\n\n### Use a token provider callback\n\nUse this approach when you want the GitHub Copilot SDK runtime to request fresh tokens on demand through a callback that you provide. The Azure Identity SDK handles token caching and refresh timing.\n\nHere are language-specific implementations:\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n<!-- docs-validate: skip -->\n\n```csharp\nusing Azure.Core;\nusing Azure.Identity;\nusing GitHub.Copilot;\n\nDefaultAzureCredential credential = new(\n    DefaultAzureCredential.DefaultEnvironmentVariableName);\nawait using CopilotClient client = new();\nstring foundryUrl = Environment.GetEnvironmentVariable(\"FOUNDRY_RESOURCE_URL\")!;\n\nawait using CopilotSession session = await client.CreateSessionAsync(new SessionConfig\n{\n    Model = \"gpt-5.5\",\n    Provider = new ProviderConfig\n    {\n        Type = \"openai\",\n        BaseUrl = $\"{foundryUrl}/openai/v1/\",\n        BearerTokenProvider = async _ =>\n        {\n            AccessToken token = await credential.GetTokenAsync(\n                new TokenRequestContext([\"https://ai.azure.com/.default\"]));\n            return token.Token;\n        },\n        WireApi = \"responses\",\n    },\n});\n\nAssistantMessageEvent? response = await session.SendAndWaitAsync(\n    new MessageOptions { Prompt = \"Hello from Managed Identity!\" });\nConsole.WriteLine(response?.Data.Content);\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n<!-- docs-validate: skip -->\n\n```golang\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy\"\n\t\"github.com/Azure/azure-sdk-for-go/sdk/azidentity\"\n\tcopilot \"github.com/github/copilot-sdk/go\"\n)\nfunc main() {\n\topts := azidentity.DefaultAzureCredentialOptions{RequireAzureTokenCredentials: true}\n\tcredential, err := azidentity.NewDefaultAzureCredential(&opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tgetBearerToken := func(args copilot.ProviderTokenArgs) (string, error) {\n\t\ttoken, err := credential.GetToken(context.Background(), policy.TokenRequestOptions{\n\t\t\tScopes: []string{\"https://ai.azure.com/.default\"},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn token.Token, nil\n\t}\n\n\tclient := copilot.NewClient(nil)\n\tif err := client.Start(context.Background()); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Stop()\n\n\tfoundryURL := os.Getenv(\"FOUNDRY_RESOURCE_URL\")\n\n\tsession, err := client.CreateSession(context.Background(), &copilot.SessionConfig{\n\t\tModel: \"gpt-5.5\",\n\t\tProvider: &copilot.ProviderConfig{\n\t\t\tType:                \"openai\",\n\t\t\tBaseURL:             fmt.Sprintf(\"%s/openai/v1/\", foundryURL),\n\t\t\tBearerTokenProvider: getBearerToken,\n\t\t\tWireAPI:             \"responses\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer session.Disconnect()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)\n\tdefer cancel()\n\n\tresponse, err := session.SendAndWait(ctx, copilot.MessageOptions{\n\t\tPrompt: \"Hello from Managed Identity!\",\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif response != nil {\n\t\tif data, ok := response.Data.(*copilot.AssistantMessageData); ok {\n\t\t\tfmt.Println(data.Content)\n\t\t}\n\t}\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nimport com.azure.core.credential.TokenRequestContext;\nimport com.azure.identity.AzureIdentityEnvVars;\nimport com.azure.identity.DefaultAzureCredentialBuilder;\nimport com.github.copilot.CopilotClient;\nimport com.github.copilot.generated.AssistantMessageEvent;\nimport com.github.copilot.rpc.BearerTokenProvider;\nimport com.github.copilot.rpc.MessageOptions;\nimport com.github.copilot.rpc.ProviderConfig;\nimport com.github.copilot.rpc.SessionConfig;\n\npublic class ManagedIdentityExample {\n    public static void main(String[] args) throws Exception {\n        var credential = new DefaultAzureCredentialBuilder()\n                .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)\n                .build();\n        BearerTokenProvider tokenProvider = providerArgs ->\n            credential\n                .getToken(new TokenRequestContext().addScopes(\"https://ai.azure.com/.default\"))\n                .map(accessToken -> accessToken.getToken())\n                .toFuture();\n        String foundryUrl = System.getenv(\"FOUNDRY_RESOURCE_URL\");\n\n        try (var client = new CopilotClient()) {\n            client.start().get();\n\n            var session = client.createSession(new SessionConfig()\n                    .setModel(\"gpt-5.5\")\n                    .setProvider(new ProviderConfig()\n                            .setType(\"openai\")\n                            .setBaseUrl(foundryUrl + \"/openai/v1/\")\n                            .setBearerTokenProvider(tokenProvider)\n                            .setWireApi(\"responses\")))\n                .get();\n\n            AssistantMessageEvent response = session\n                    .sendAndWait(new MessageOptions().setPrompt(\"Hello from Managed Identity!\"))\n                    .get();\n            System.out.println(response.getData().content());\n\n            session.disconnect().get();\n        }\n    }\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n<!-- docs-validate: skip -->\n\n```python\nimport asyncio\nimport os\n\nfrom azure.identity.aio import DefaultAzureCredential\nfrom copilot import CopilotClient\nfrom copilot.session import PermissionHandler, ProviderConfig\n\nasync def main():\n    credential = DefaultAzureCredential(require_envvar=True)\n    async def get_bearer_token(_args) -> str:\n        token = await credential.get_token(\"https://ai.azure.com/.default\")\n        return token.token\n\n    foundry_url = os.environ[\"FOUNDRY_RESOURCE_URL\"]\n\n    client = CopilotClient()\n    await client.start()\n\n    session = await client.create_session(\n        on_permission_request=PermissionHandler.approve_all,\n        model=\"gpt-5.5\",\n        provider=ProviderConfig(\n            type=\"openai\",\n            base_url=f\"{foundry_url.rstrip('/')}/openai/v1/\",\n            bearer_token_provider=get_bearer_token,\n            wire_api=\"responses\",\n        ),\n    )\n\n    response = await session.send_and_wait(\"Hello from Managed Identity!\")\n    print(response.data.content)\n\n    await client.stop()\n    await credential.close()\n\nasyncio.run(main())\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n<!-- docs-validate: skip -->\n\n```rust\nuse std::sync::Arc;\n\nuse azure_core::credentials::TokenCredential;\nuse azure_identity::{DeveloperToolsCredential, ManagedIdentityCredential};\nuse github_copilot_sdk::{BearerTokenError, Client, ClientOptions, MessageOptions, ProviderTokenArgs};\nuse github_copilot_sdk::types::{ProviderConfig, SessionConfig};\n\nfn credential_for_environment() -> azure_core::Result<Arc<dyn TokenCredential>> {\n    match std::env::var(\"AZURE_TOKEN_CREDENTIALS\").as_deref() {\n        Ok(\"ManagedIdentityCredential\") => Ok(ManagedIdentityCredential::new(None)?),\n        _ => Ok(DeveloperToolsCredential::new(None)?),\n    }\n}\n\n#[tokio::main]\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n    let credential = credential_for_environment()?;\n    let foundry_url = std::env::var(\"FOUNDRY_RESOURCE_URL\")?;\n\n    let get_bearer_token = {\n        let credential = credential.clone();\n        move |_args: ProviderTokenArgs| {\n            let credential = credential.clone();\n            async move {\n                let token = credential\n                    .get_token(&[\"https://ai.azure.com/.default\"], None)\n                    .await\n                    .map_err(|err| BearerTokenError::message(err.to_string()))?;\n                Ok(token.token.secret().to_string())\n            }\n        }\n    };\n\n    let mut provider = ProviderConfig::default();\n    provider.provider_type = Some(\"openai\".to_string());\n    provider.base_url = format!(\"{}/openai/v1/\", foundry_url.trim_end_matches('/'));\n    provider.bearer_token_provider = Some(Arc::new(get_bearer_token));\n    provider.wire_api = Some(\"responses\".to_string());\n\n    let mut config = SessionConfig::default();\n    config.model = Some(\"gpt-5.5\".to_string());\n    config.provider = Some(provider);\n\n    let client = Client::start(ClientOptions::default()).await?;\n    let session = client.create_session(config).await?;\n\n    session\n        .send_and_wait(MessageOptions::new(\"Hello from Managed Identity!\"))\n        .await?;\n\n    session.disconnect().await?;\n    client.stop().await?;\n    Ok(())\n}\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n<!-- docs-validate: skip -->\n\n```typescript\nimport { DefaultAzureCredential } from \"@azure/identity\";\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\nconst credential = new DefaultAzureCredential({\n  requiredEnvVars: [\"AZURE_TOKEN_CREDENTIALS\"],\n});\nconst getBearerToken = async () => {\n  const tokenResponse = await credential.getToken(\"https://ai.azure.com/.default\");\n  return tokenResponse.token;\n};\n\nconst client = new CopilotClient();\n\nconst session = await client.createSession({\n  model: \"gpt-5.5\",\n  provider: {\n    type: \"openai\",\n    baseUrl: `${process.env.FOUNDRY_RESOURCE_URL}/openai/v1/`,\n    bearerTokenProvider: getBearerToken,\n    wireApi: \"responses\",\n  },\n});\n\nconst response = await session.sendAndWait({ prompt: \"Hello from Managed Identity!\" });\nconsole.log(response?.data.content);\n\nawait client.stop();\n```\n\n</div>\n\n</div>\n\n## Environment configuration\n\n| Variable                  | Description                                                                                                                                                                                               | Example                                  |\n| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- |\n| `AZURE_TOKEN_CREDENTIALS` | When running in **Azure**, set it to `ManagedIdentityCredential`. When running **locally**, set it to either `dev` or a developer tool credential name, such as `AzureCliCredential`.                     | `ManagedIdentityCredential`              |\n| `AZURE_CLIENT_ID`         | *Optional.* When running in **Azure**, set this to the client ID of a User-assigned Managed Identity when using `ManagedIdentityCredential`. If not set, Azure uses the System-assigned Managed Identity. | `11111111-2222-3333-4444-555555555555`   |\n| `FOUNDRY_RESOURCE_URL`    | Your Microsoft Foundry resource URL                                                                                                                                                                       | `https://<my-resource>.openai.azure.com` |\n\nNo API key environment variable is needed—authentication is handled by Azure Identity credentials. In .NET, Go, Java, Python, and TypeScript, `DefaultAzureCredential` automatically supports:\n\n* **Managed Identity** (System-assigned or User-assigned): for Azure-hosted apps\n* **Azure CLI** (`az login`): for local development\n* **Environment variables** (`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`): for service principals\n* **Workload Identity**: for Kubernetes\n\nIn .NET, Go, Java, Python, and TypeScript, `ManagedIdentityCredential` reads `AZURE_CLIENT_ID` to select a User-assigned Managed Identity. Rust is an exception in this guide.\n\nIn Rust, use `DeveloperToolsCredential` for local development and `ManagedIdentityCredential` when running in Azure. For other languages, see the `DefaultAzureCredential` documentation for the full credential chain:\n\n* [.NET](https://aka.ms/azsdk/net/identity/credential-chains#defaultazurecredential-overview)\n* [Go](https://aka.ms/azsdk/go/identity/credential-chains#defaultazurecredential-overview)\n* [Java](https://aka.ms/azsdk/java/identity/credential-chains#defaultazurecredential-overview)\n* [Python](https://aka.ms/azsdk/python/identity/credential-chains#defaultazurecredential-overview)\n* [TypeScript](https://aka.ms/azsdk/js/identity/credential-chains#defaultazurecredential-overview)\n\n## When to use this pattern\n\n| Scenario                                            | Recommendation                                                               |\n| --------------------------------------------------- | ---------------------------------------------------------------------------- |\n| Azure-hosted app with Managed Identity              | ✅ Use this pattern                                                           |\n| App with existing Microsoft Entra service principal | ✅ Use this pattern                                                           |\n| Local development with `az login`                   | ✅ Use this pattern                                                           |\n| Non-Azure environment with static API key           | Use [BYOK (bring your own key)](/en/copilot/how-tos/copilot-sdk/auth/byok)   |\n| GitHub Copilot subscription available               | Use [GitHub OAuth setup](/en/copilot/how-tos/copilot-sdk/setup/github-oauth) |\n\n## See also\n\n* [BYOK (bring your own key)](/en/copilot/how-tos/copilot-sdk/auth/byok): Static API key configuration\n* [Backend services setup](/en/copilot/how-tos/copilot-sdk/setup/backend-services): Server-side deployment"}