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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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“); | |
} |