EF核心连接到具有托管身份的Azure SQL [英] EF Core Connection to Azure SQL with Managed Identity

查看:65
本文介绍了EF核心连接到具有托管身份的Azure SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF Core连接到部署到Azure App Services的Azure SQL数据库.我正在使用访问令牌(通过托管身份获取)来连接到Azure SQL数据库.

I am using EF Core to connect to a Azure SQL Database deployed to Azure App Services. I am using an access token (obtained via the Managed Identities) to connect to Azure SQL database.

这是我的做法:

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

这工作正常,我可以从数据库中获取数据.但是我不确定这是否是正确的方法.

This works fine and I can get data from the database. But I am not sure if this is the right way to do it.

我的问题:

  1. 这是正确的方法吗?还是会出现性能问题?
  2. 我需要担心令牌到期吗?到目前为止,我还没有缓存令牌.
  3. EF Core是否有更好的方法来处理此问题?

推荐答案

这是正确的方法吗?还是会出现性能问题?

Is this a right way to do it or will it have issues with performance?

那是正确的方法.每个新的DbContext都会调用OnConfiguring,因此,假设您没有任何长期存在的DbContext实例,那么这是正确的模式.

That is the right way. OnConfiguring is called for each new DbContext, so assuming you don't have any long-lived DbContext instances, this is the right pattern.

我需要担心令牌到期吗?到目前为止,我还没有缓存令牌.

Do I need to worry about token expiration? I am not caching the token as of now.

AzureServiceTokenProvider负责缓存.

EF Core是否有更好的方法来处理此问题?

Does EF Core has any better way to handle this?

设置SqlConnection.AccessToken是当前在SqlClient for .NET Core中使用AAD Auth的唯一方法.

Setting the SqlConnection.AccessToken is currently the only way of using AAD Auth in SqlClient for .NET Core.

这篇关于EF核心连接到具有托管身份的Azure SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆