Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# snippet for connecting to an Azure DB instance via access token in a .NET Core app
{
"DefaultConnection": "Server=tcp:mydbserver.database.windows.net,1433;Database=mydb;"
}
using Microsoft.Azure.Services.AppAuthentication;
using System.Data.SqlClient;
namespace MyApp.Infrastructure.EntityFramework
{
public class MyDbContext : DbContext
{
public MyDbContext()
{
var conn = (SqlConnection)this.Database.GetDbConnection();
conn.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
}
}
}
@phsantiago32
Copy link
Author

phsantiago32 commented Sep 24, 2019

Steps:

  1. Target .NET 2.2 (minimum)
  2. Install NuGet Package Microsoft.Azure.Services.AppAuthentication
  3. Change connection string
  4. Add the code snippet to the constructor of your DbContext class

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment