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

使用C#通过AAD连接Azure SQL数据库失败求助

Azure SQL AAD认证C#代码连接失败问题

我们DevOps团队近期在Azure SQL Server中启用了AAD认证,并将我的身份my.identity@mycompany.com添加为MyDatabase的dbo。我可以通过SSMS成功连接该数据库,但使用C#代码以同一身份连接时失败。

我的代码:

using System; 
using System.Threading.Tasks; 
using System.Data.SqlClient; 
using Microsoft.Azure.Services.AppAuthentication; 

namespace AzureADAuth { 
    class Program { 
        static async Task Main(string[] args) { 
            var azureServiceTokenProvider = new AzureServiceTokenProvider(); 
            string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/"); 
            Principal principal = azureServiceTokenProvider.PrincipalUsed; 
            Console.WriteLine($"AppId: {principal.AppId}"); 
            Console.WriteLine($"IsAuthenticated: {principal.IsAuthenticated}"); 
            Console.WriteLine($"TenantId: {principal.TenantId}"); 
            Console.WriteLine($"Type: {principal.Type}"); 
            Console.WriteLine($"UserPrincipalName: {principal.UserPrincipalName}"); 

            using (var connection = new SqlConnection("Data Source=########.database.windows.net; Initial Catalog=MyDatabase;")) { 
                connection.AccessToken = accessToken; 
                await connection.OpenAsync(); 
                var command = new SqlCommand("select CURRENT_USER", connection); 
                using (SqlDataReader reader = await command.ExecuteReaderAsync()) { 
                    await reader.ReadAsync(); 
                    Console.WriteLine(reader.GetValue(0)); 
                } 
            } 
            Console.ReadKey(); 
        } 
    } 
}

程序输出:

AppId: 
IsAuthenticated: True 
TenantId: ########-####-####-bc14-789b44d11a3c 
Type: User 
UserPrincipalName: my.identity@mycompany.com 

Unhandled Exception: System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. 
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)

补充说明:

  • 使用的是.NET Full Framework 4.7
  • Microsoft.Azure.Services.AppAuthentication包为最新版本1.0.1
  • 我的机器未加入任何域(不确定是否重要,我仅需要基于令牌的认证,而非AAD集成认证)

问题排查与解决

兄弟,你这问题我之前踩过同款坑!核心原因特别直白:你获取的AccessToken是给Azure管理API用的,根本不是Azure SQL认的!

你看代码里调用GetAccessTokenAsync时传的是https://management.azure.com/,这个资源标识符是给Azure资源管理器服务用的,但Azure SQL有自己专属的资源标识https://database.windows.net/,SQL Server不认你当前拿的这个token,自然就报匿名登录失败了。

具体修复步骤:

  1. 修正资源标识符
    把获取token的那行代码改成下面这样:
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/");

这样拿到的token受众(aud字段)会是https://database.windows.net/,完全符合Azure SQL的认证要求。

  1. 验证修改后的效果
    改完重新运行代码,应该就能成功连接数据库,执行select CURRENT_USER会返回你的AAD账号my.identity@mycompany.com。

  2. 额外注意事项

  • 你的.NET 4.7环境默认支持TLS 1.2,而Azure SQL现在强制要求至少TLS 1.2,这部分不用额外配置;如果后续遇到TLS相关问题,再检查系统的TLS版本设置即可
  • 你用Azure CLI获取身份的方式没问题,AzureServiceTokenProvider会自动优先使用CLI的身份上下文,这部分你已经验证能拿到正确的UPN,不用调整其他配置

修改后的核心代码片段:

var azureServiceTokenProvider = new AzureServiceTokenProvider();
// 关键修改:切换为SQL专属的资源标识符
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/");
Principal principal = azureServiceTokenProvider.PrincipalUsed;
// 后续代码保持不变...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:04:39