如何将Azure MSI AccessToken添加到EF6 DbContext中以连接Azure SQL PaaS

问题描述 投票:0回答:1

使用MVC和EF6代码优先方法,我能够集成Azure MSI令牌并执行CRUD操作,但是如何执行必须将令牌注入DBContext的迁移:

连接字符串:enter image description here

对于执行CRUD查询,我使用传统的ADO.NET样式查询,如下所示,它的工作原理是:enter image description here

获取MSI:enter image description here为了运行迁移,如何将Azure MSI AccessToken传递到DbContext建设者中。enter image description here

对于dbcontext,我必须使用提供程序名称定义单独的连接字符串。enter image description here

c# azure entity-framework
1个回答
0
投票

您需要在DI中进行设置:

Startup.cs

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

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

DbContext

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

    public AzureProvider(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<AzureProvider> 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);
    }
}


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

© www.soinside.com 2019 - 2024. All rights reserved.