問題描述
我正在使用 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 連接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!