Skip to content

Instantly share code, notes, and snippets.

@phsantiago32
Created August 2, 2019 17:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phsantiago32/181e6b1bcf244d6990f1873a62c8d103 to your computer and use it in GitHub Desktop.
Save phsantiago32/181e6b1bcf244d6990f1873a62c8d103 to your computer and use it in GitHub Desktop.
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

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

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