EF Core 和 Azure SQL 具有托管身份(无 `IDBAuthTokenService`)

EF Core & Azure SQL with Managed Identity (no `IDBAuthTokenService`)

我正在尝试连接到部署到 Azure 应用服务的 Azure SQL 数据库。从本质上讲,我正在尝试从 2019 年 1 月开始执行 [this question][1] 中描述的操作,但 IDBAuthTokenService 不存在于 Microsoft.Azure.Services.AppAuthentication 中(即使存在,也没有任何参考)。

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;
    }
}

[

您可以使用 Microsoft.Azure.Services.AppAuthentication



Startup.cs

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

在你的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);
}