问题描述
我正在使用 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.
我的问题:
- 这是一种正确的方法吗?还是会出现性能问题?
- 我需要担心令牌过期吗?我现在没有缓存令牌.
- 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 是目前在 .NET Core 的 SqlClient 中使用 AAD Auth 的唯一方法.
Setting the SqlConnection.AccessToken is currently the only way of using AAD Auth in SqlClient for .NET Core.
这篇关于使用托管标识与 Azure SQL 的 EF Core 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!