Reputation: 755
I am using Npgsql and EF Core (3.1) in a Net Framework 4.8 application. Due to company infrastructure/policy, I cannot upgrade any higher. I am connecting to the database using an Azure Managed Identity. I am using Unity for Dependency Injection.
All of this is working perfectly fine, except that after an hour my Managed Identity AccessToken, which is used as the password for the db-connection, expires. And then obviously the connection is no longer valid either. Is there an elegant way to solve this?
During startup I generate an AccessToken for my Managed Identity:
HttpClient httpClient = new HttpClient();
FormUrlEncodedContent content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", ClientId),
new KeyValuePair<string, string>("client_secret", Secret),
new KeyValuePair<string, string>("scope", "https://management.azure.com/.default"),
});
var tokenUrl = $"https://login.microsoftonline.com/{TenantId}/oauth2/token";
var response = await httpClient.PostAsync(tokenUrl, content);
var result = await response.Content.ReadAsStringAsync();
AccessTokenResponse accessTokenResponse = JsonSerializer.Deserialize<AccessTokenResponse>(result);
return accessTokenResponse.AccessToken;
Which I then use the create the connection string in code
// params provided to method
return String.Format("Server={0};Database={1};Port={2};User Id={3};Password={4};SSLMode=Prefer",
databaseHost,
databaseName,
5432,
databaseUser,
accessToken);
And lastly I use Unity to add the Npgsql DbContext:
var optionsBuilder = new DbContextOptionsBuilder<DbContext>();
optionsBuilder.UseNpgsql(connectionString: databaseConnectionString,
npgsqlOptionsAction: o =>
{
o.UseNetTopologySuite();
o.CommandTimeout(3600);
})
// IUnityContainer
container.RegisterInstance(optionsBuilder.Options);
Upvotes: 0
Views: 191
Reputation: 16672
Newer versions of Npgsql have specific features for access token rotation (docs); but such an old version does not (note that 3.1 is out of support at this point). You'll likely have to manually rebuild your connection string when the auth token changes, and ensure that's used everywhere.
Upvotes: 0