我們的開發人員最近在我們的 Azure SQL Server 中啟用了 AAD 身份驗證,并將我的身份(比如[email protected])作為 dbo 添加到MyDatabase。我可以使用 SSMS 成功連接到數據庫,現在我想使用代碼中的相同身份進行連接: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: TrueTenantId: ########-####-####-bc14-789b44d11a3cType: UserUserPrincipalName: [email protected]我的目標是 .NET 完整框架 4.7;Microsoft.Azure.Services.AppAuthentication包是最新的,1.0.1;我的機器沒有加入任何域(不確定它是否重要,因為我不需要 AAD 集成身份驗證,只需要基于令牌)
2 回答

慕絲7291255
TA貢獻1859條經驗 獲得超6個贊
對于遇到此問題的任何人 - 我搜索了多個資源,其中用戶遇到了這個確切的問題,但沒有有效的解決方案。但是,最終通過添加我的 SQL 數據庫所在位置的“租戶”來解決我的問題。因為我有多個 Azure 訂閱。
在上面的代碼中獲取token:
return provider.GetAccessTokenAsync("https://database.windows.net/");
我還需要添加租戶:
return provider.GetAccessTokenAsync("https://database.windows.net/", "hosttenant.onmicrosoft.com");
- 2 回答
- 0 關注
- 273 瀏覽
添加回答
舉報
0/150
提交
取消