Chasing DevOps

A blog about software development, DevOps, and delivering value.

Using Azure.Identity to Connect to Azure SQL

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 =;Database=MyDatabase;
var cred = new DefaultAzureCredential();
// Get access token. The scope for Azure SQL is
var token = cred.GetToken(new TokenRequestContext(
new string[] { }));
using(var connection = new SqlConnection(connString))
// Set the token
conn.AccessToken = token.Token;
// 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

Leave a Reply

Your email address will not be published. Required fields are marked *

Jesse Barocio

Software developer, DevOps engineer, and productivity tool nut. Continuously improving. Have a question or problem you need solved? Email me!