I have an on-premise console application through which I am accessing Azure SQL Server. Currently I am using the user name/password connection string to connect to Azure SQL.
I would like to use the managed identity to connect to Azure SQL from the on-premise console application.
Please let me know if it is possible and how it can be done.
0
According to this
You cannot use Managed Identity (both system assigned and user assigned) outside of Azure. They can only be used with resources running in Azure.
So, it is not possible to connect Azure SQL database to on-premises console app with managed identity authentication. Alternatively, you can use Azure active directory interactive. So, you can use below connection sting:
Server=tcp:<serverNmae>.database.windows.net,1433;Initial Catalog=<databaseName>;Persist Security Info=False;User ID=<ADId>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication="Active Directory Interactive";
Here is the complete code:
using System;
using System.Data;
using Microsoft.Data.SqlClient;
string connectionString = "Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<databaseName>;Persist Security Info=False;User ID=<ADId>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication="Active Directory Interactive";";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM <tableName>";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int studentId = reader.GetInt32(reader.GetOrdinal("Id"));
string Name = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine($"StudentID: {studentId}, Name: {Name}");
}
}
}
}
It will open browser for authentication for the first time. after that it will connect automatically after connecting. The database is connected successfully as shown below:
Along with that you can use service principle authentication to connect Azure SQL database.