Skip to content

Instantly share code, notes, and snippets.

@jessebarocio
Created September 26, 2020 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessebarocio/c2d871cd565de5b504eaf54ca51ca7d9 to your computer and use it in GitHub Desktop.
Save jessebarocio/c2d871cd565de5b504eaf54ca51ca7d9 to your computer and use it in GitHub Desktop.
Using Azure.Identity to Connect to Azure SQL
// 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");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment