I have an ASP.NET Core 9 Web API which I need to use managed identity to connect to a postgres database.
I have this code in my Program.cs
and I converted them from
var connectionString = builder.Configuration.GetConnectionString("db_conn_string")!;
builder.Services.AddEntityFrameworkNpgsql().AddDbContext<MyDbContext>(options =>
options.UseNpgsql(connectionString)
);
to this after following this document. But there the example is for console app not for Web API:
var connectionString = builder.Configuration.GetConnectionString("db_conn_string")!;
if (builder.Configuration["ASPNETCORE_ENVIRONMENT"] != "Development")
{
var accessToken = await new DefaultAzureCredential().GetTokenAsync(
new TokenRequestContext(scopes: [
"/.default"
])
);
connectionString = $"{builder.Configuration.GetConnectionString("db_conn_string")};Password={accessToken.Token}";
}
builder.Services.AddEntityFrameworkNpgsql().AddDbContext<MyDbContext>(options =>
options.UseNpgsql(connectionString)
);
But this will only work once right because I'm setting the token first time and after first token expire and getting new refreshed token it is not reset in connection string even though it says that in here
Token lifetime and refreshing is handled automatically. Where possible, reuse credential instances to optimize cache effectiveness
Links i thought are useful but dont know how to continue
- link 1
- link 2
- link 3
I'm new to these things - can someone help me with this?