1
votes

I'm trying to connect to an Azure SQL Database deployed to Azure App Services. Essentially I'm trying to do what is described in [this question][1] from January 2019, but IDBAuthTokenService does not exist in Microsoft.Azure.Services.AppAuthentication (if it ever did, there are no references anywhere).

  • What is the right way to do this now?

  • Should I ditch DbContext and create a ConnectionFactory myself instead? (I've seen a colleague do this, but using DbContext seems like the idiomatic way to do it in EF Core).

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    //code ignored for simplicity
    services.AddDbContext<MyCustomDBContext>();

    services.AddTransient<IDBAuthTokenService, AzureSqlAuthTokenService>();
}

MyCustomDBContext.cs

public partial class MyCustomDBContext : DbContext
{
    public IConfiguration Configuration { get; }
    public IDBAuthTokenService authTokenService { get; set; }

    public MyCustomDbContext(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<MyCustomDBContext> options)
        : base(options)
    {
        Configuration = configuration;
        authTokenService = tokenService;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
        connection.AccessToken = authTokenService.GetToken().Result;

        optionsBuilder.UseSqlServer(connection);
    }
}

AzureSqlAuthTokenService.cs

public class AzureSqlAuthTokenService : IDBAuthTokenService
{
    public async Task<string> GetToken()
    {
        AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
        var token = await provider.GetAccessTokenAsync("https://database.windows.net/");

        return token;
    }
}

[EF Core Connection to Azure SQL with Managed Identity

1

1 Answers

0
votes

You may use Microsoft.Azure.Services.AppAuthentication

enter image description here



In Startup.cs

services.AddSingleton<AzureServiceTokenProvider>(new AzureServiceTokenProvider());
services.AddDbContext<SqlDBContext>();

In your DbContext.cs :

private AzureServiceTokenProvider azureServiceTokenProvider;
public SqlDBContext(DbContextOptions<SqlDBContext> options, AzureServiceTokenProvider azureServiceTokenProvider) : base(options)
{
    this.azureServiceTokenProvider = azureServiceTokenProvider;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = "Data Source=tcp:jackdemo.database.windows.net,1433; Initial Catalog=jackdemo; "; 
    connection.AccessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/").Result;
    optionsBuilder.UseSqlServer(connection);
}