如何将 Azure 数据库与具有 MFA 支持的 Active Directory-Universal .Net Core 连接

How to connect Azure database with Active Directory-Universal with MFA Support .Net Core

我正在尝试连接到 Azure 数据库。 我当前的连接字符串 "return $"密码={this.Password}; Persist Security Info=True;User ID = { this.User };初始目录 = { this.Database };数据源 = { this.Server }";"像这样。如何使用支持 MFA 的 Active Directory-Universal 连接到 Azure 数据库

如果要将 Azure SQL 数据库与具有 MFA 的 Active Directory-Universal 连接,您可以将 SQL 数据库与 Azure AD 访问令牌连接。例如 1.注册一个网络应用程序

  1. 配置权限

  2. 代码(我使用ADAL获取访问令牌) 静态无效主要(字符串[]参数) {

        string authory = "https://login.microsoftonline.com/hanxia.onmicrosoft.com";
    
        AuthenticationContext authContext = new AuthenticationContext(authory);
    
        Console.WriteLine("get token");
        var result = GetTokenViaCode(authContext).Result;
    
        var connection = new SqlConnection("Data Source=[my database].database.windows.net;Initial Catalog=[my initial catalog];");
        connection.AccessToken = result.AccessToken;
        connection.Open();
    
        Console.WriteLine();
    }
    
    static async Task<AuthenticationResult> GetTokenViaCode(AuthenticationContext ctx)
    {
        string resource = "https://database.windows.net";
        string clientId = "2c4aae8f-392c-419a-b454-8f8c1ff1ec0c";
        AuthenticationResult result = null;
        try
        {
            DeviceCodeResult codeResult = await ctx.AcquireDeviceCodeAsync(resource, clientId);
            Console.ResetColor();
            Console.WriteLine("You need to sign in.");
            Console.WriteLine("Message: " + codeResult.Message + "\n");
            result = await ctx.AcquireTokenByDeviceCodeAsync(codeResult);
        }
        catch (Exception exc)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Something went wrong.");
            Console.WriteLine("Message: " + exc.Message + "\n");
        }
        return result;
    }
    

请注意,我在控制台应用程序中对其进行了测试,因此我使用设备代码流来获取访问令牌。如果你想在 web 应用程序中使用它,你可以使用 OpenID 流来实现它。更多详情请参考sample