亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法從 C# 使用 AAD 連接到 Azure SQL 數據庫

無法從 C# 使用 AAD 連接到 Azure SQL 數據庫

C#
Helenr 2021-06-03 09:41:42
我們的開發人員最近在我們的 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");



查看完整回答
反對 回復 2021-06-05
  • 2 回答
  • 0 關注
  • 273 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號