Using Azure.Identity to Connect to Azure SQL

September 17, 2020

The new Azure.Identity library hit GA this month. I’ve been wanting to modify a lot of our services to use managed identities and this library, through the use of DefaultAzureIdentity, finally streamlines the experience between local development and running in Azure.

So far only the most common Azure SDK packages have first class support for it, but more are on the way. The first thing I wanted to get working with it was some SQL database queries. Below is some sample code that shows how to make this happen.

// No credentials needed in the connection string!
var connString = "Server=myserver.database.windows.net;Database=MyDatabase";
var cred = new DefaultAzureCredential();
// Get access token. The scope for Azure SQL is https://database.windows.net.
var token = cred.GetToken(new TokenRequestContext(
new string[] { "https://database.windows.net" }));
using(var connection = new SqlConnection(connString))
{
// Set the token
conn.AccessToken = token.Token;
conn.Open();
// Execute your SQL commands
var count = conn.ExecuteScalar<int>("SELECT COUNT(*) FROM Tenants");
Console.WriteLine($"There are {count} tenants");
}
view raw Connect.cs hosted with ❤ by GitHub


© 2020 Jesse Barocio. Built with Gatsby