EF Core 通过托管标识连接到 Azure SQL [英] EF Core Connection to Azure SQL with Managed Identity

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

问题描述

我正在使用 EF Core 连接到部署到 Azure 应用服务的 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 身份验证的唯一方法.

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

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

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