You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中获取Azure服务主体的Bearer Token(无需Azure CLI)

我来帮你搞定这个问题!不用Azure CLI的话,有两种靠谱的方式可以获取服务主体的Bearer令牌,分别是用Azure .NET SDK(推荐)和直接调用Azure AD的REST接口,下面给你详细讲:

方法一:使用Azure .NET SDK(推荐)

这种方式更符合.NET生态的最佳实践,而且SDK会帮你处理令牌缓存、过期自动刷新等细节,不用自己操心。

步骤1:安装NuGet包

首先需要安装Azure.Identity包,这是Azure官方的身份验证SDK:

Install-Package Azure.Identity

或者用.NET CLI:

dotnet add package Azure.Identity

步骤2:编写C#代码

替换代码里的tenantId、clientId、clientSecret为你的实际值,scope用和Azure CLI一致的https://management.azure.com/.default,这样拿到的令牌权限和CLI获取的完全匹配:

using Azure.Identity;
using System;

class Program
{
    static async Task Main(string[] args)
    {
        // 替换为你的实际参数
        string tenantId = "你的tenant_id";
        string clientId = "你的client_id";
        string clientSecret = "你的client_secret";
        // 与Azure CLI默认scope一致,确保权限匹配
        string[] scopes = new[] { "https://management.azure.com/.default" };

        // 创建服务主体身份凭证
        var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        
        // 获取Bearer令牌
        var tokenResult = await credential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes));
        
        Console.WriteLine("获取到的Bearer令牌:");
        Console.WriteLine(tokenResult.Token);
        Console.WriteLine($"令牌过期时间:{tokenResult.ExpiresOn}");
    }
}
方法二:直接调用Azure AD REST API

如果不想依赖SDK,也可以直接发送HTTP请求到Azure AD的令牌端点,这种方式更灵活,适合需要自定义请求的场景。

步骤1:准备请求参数

请求端点为:https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token,需要发送POST请求,参数用form-data格式传递。

步骤2:编写C#代码

这里需要用到Newtonsoft.Json来解析返回的JSON(可以通过NuGet安装):

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class Program
{
    static async Task Main(string[] args)
    {
        string tenantId = "你的tenant_id";
        string clientId = "你的client_id";
        string clientSecret = "你的client_secret";
        string scope = "https://management.azure.com/.default";

        using var httpClient = new HttpClient();
        var requestParams = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = clientId,
            ["client_secret"] = clientSecret,
            ["scope"] = scope
        });

        // 发送POST请求获取令牌
        var response = await httpClient.PostAsync(
            $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token", 
            requestParams
        );
        
        // 确保请求成功,失败时抛出异常
        response.EnsureSuccessStatusCode();

        // 解析返回的JSON,提取access_token
        var responseContent = await response.Content.ReadAsStringAsync();
        var jsonResponse = JObject.Parse(responseContent);
        string accessToken = jsonResponse["access_token"].ToString();
        int expiresIn = jsonResponse["expires_in"].Value<int>();

        Console.WriteLine("获取到的Bearer令牌:");
        Console.WriteLine(accessToken);
        Console.WriteLine($"令牌有效期(秒):{expiresIn}");
    }
}
一些重要提示
  • 敏感信息安全:绝对不要把client_secret硬编码到代码里,建议用appsettings.json、环境变量或者Azure Key Vault来存储这些敏感数据。
  • Scope调整:如果需要访问其他Azure服务,要替换对应的scope,比如访问Azure存储的scope是https://storage.azure.com/.default,访问Graph API是https://graph.microsoft.com/.default。
  • 令牌过期:两种方式都能获取到令牌的过期时间,记得在令牌过期前重新获取,SDK方法会自动帮你处理缓存和刷新。

内容的提问来源于stack exchange,提问作者Dzior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:35:55