I am trying to connect to azure database. My current connection string "return $"Password={this.Password}; Persist Security Info=True;User ID = { this.User }; Initial Catalog = { this.Database }; Data Source = { this.Server }";" like this. How can I connect to azure database with Active Directory-Universal with MFA Support
If you want to connect Azure SQL Database with Active Directory-Universal with MFA, you can connect your SQL database with Azure AD access token. For example 1. Register a web application
Code( I use ADAL to get access token) static void Main(string[] args) {
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;
}
Please note that I test it in console application, so I use device code flow to get access token. If you want to use it in web app, you can use OpenID flow to implememnt it. For more deatils, please refer to the sample.