45
loading...
This website collects cookies to deliver better user experience
Microsoft.Data.SqlClient
v3.0.0, a new authentication mode Active Directory Default
has been released. Let's see what this means when querying an Azure SQL Database from some C# code.🗨 If you do not have heard about Microsoft.Data.SqlClient
, it is the new data provider for Microsoft SQL Server and Azure SQL Database which supports both .NET Framework and .NET Core and replace the old System.Data.SqlClient
components.
tradidional way
to connect to an Azure SQL database from an application in C# is to provide to the SqlConnection
constructor a connection string that contains a username and a password. The corresponding C# code is quite simple:var connectionString = "Server=server-testingmsi6499.database.windows.net; Database=database-testingmsi6499;User ID=globalSqlAdmin;Password=MySecretPassword;");
using (var sqlConnection = new SqlConnection(connectionString));
await connection.OpenAsync();
Azure Key Vault
.SqlConnection
instance:var accessToken = await new DefaultAzureCredential().GetTokenAsync(new TokenRequestContext(new string[] { "https://database.windows.net//.default" }));
using var connection = new SqlConnection("Server=server-testingmsi6499.database.windows.net; Database=database-testingmsi6499;")
{
AccessToken = accessToken.Token
};
await connection.OpenAsync();
DefaultAzureCredential
from Azure Identity library combines multiple authentication mechanisms (like Managed Identities, Visual Studio, Azure CLI ...) that will be tried in order to retrieve a token so it is practical class which can handle most of the scenarios.Active Directory Default
new authentication mode was introduced in Microsoft.Data.SqlClient
v3.0.0. Under the hood, SqlClient
does the exact same thing that we were showing previously so we don't have to do it ourselves: just specifying the authentication mode to Active Directory Default
in the connection string is enough to make it work.using var connection = new SqlConnection("Server=server-testingmsi6499.database.windows.net; Authentication=ActivDirectory Default; Database=database-testingmsi6499;");
await connection.OpenAsync();
🗨 There are other Azure Active Directory authentication methods available, you can find them in the documentation here.
#!/bin/bash
location="West Europe" # to change with your preferred location
randomIdentifier=testingmsi${RANDOM:0:5}
resourceGroup="resource-$randomIdentifier"
server="server-$randomIdentifier"
database="database-$randomIdentifier"
login="globalSqlAdmin"
password="P@ssw0rdToChange!" # to change to have a more secured password
# Retrieve your public IP.
# Replace by your local machine IP if your are executing this script from cloud shell.
startIP=$(dig +short myip.opendns.com @resolver1.opendns.com)
endIP=$startIP
# Retrieve your current logged in user to be used as sql server admin.
# Change with another user id if you want another user to be admin.
azureaduser=$(az ad signed-in-user show --query "objectId" -o tsv)
echo "Creating $resourceGroup..."
az group create --name $resourceGroup --location "$location"
echo "Creating $server in $location..."
az sql server create --name $server --resource-group $resourceGroup --location "$location" --admin-user $login --admin-password $password
echo "Configuring firewall..."
az sql server firewall-rule create --resource-group $resourceGroup --server $server -n AllowYourIp --start-ip-address $startIP --end-ip-address $endIP
echo "Creating $database on $server..."
az sql db create --resource-group $resourceGroup --server $server --name $database --sample-name AdventureWorksLT --service-objective Basic --zone-redundant false
echo "Creating AD admin in sql server..."
az sql server ad-admin create --resource-group $resourceGroup --server-name $server --display-name ADMIN --object-id $azureaduser
echo "Database connection string to use: \"Server=$server.database.windows.net; Authentication=Active Directory Default; Database=$database;\""
startIP
variable by your local machine IP)🗨 If you are new to Azure CLI, you can read my article Good bye Azure Portal, Welcome Azure CLI.
Program.cs
file, so it's very convenient when you want to quickly build a web application without too much complexity (especially if you are new to ASP.NET Core) or if you are developing a small microservice.using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.MapGet("/", (Func<Task<IEnumerable<Product>>>)(async () =>
{
using var connection = new SqlConnection("Server=server-testingmsi6499.database.windows.net; Authentication=Active Directory Default; Database=database-testingmsi6499;");
var products = await connection.QueryAsync<Product>("SELECT TOP 10 ProductID, Name from [SalesLT].[Product]");
return products;
}));
app.Run();
public record Product(int ProductID, string Name);
[SalesLT].[Product]
of the database created with the previous Azure CLI scriptProduct
which is declared in one lineMicrosoft.Data.SqlClient
v3.0.0 with the Active Directory Default
authentication mode
🗨 To keep things simple, I am connecting to the database with the my Azure AD account which is admin of the sql server. But I could also have assigned a role with lower permissions to my account, see here for more information on how to do that.
Microsoft.Data.Sql.Client
or the Azure SDKs allow us to do that quite easily. I love how connecting to an Azure SQL Database in C# is becoming more simple and more secure at the same time.