I am using Entity Framework to connect to an Azure SQL database and I'm connecting using an access token (obtained via the Managed Identities).
I am not using user name and password in the SQL connection string and using managed identity and keeping SQL connection string in Azure keyvault.
I'm connecting to the database with a token like shown below, but after an hour it expires, so I'm getting "SQL login failed - " errors.
I have a long running process once connected the the database, and it collects some config data from some tables, and after more than 45 minutes, I need to update data in the database. When trying to save changes using dbcontext, the code is throwing this timeout issue.
How to get a new refreshed token and set to connection?
public SqlConnection GetDBConnection()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
var credential = new DefaultAzureCredential();
var accessToken = credential.GetToken(new TokenRequestContext(new[] { "https://database.windows.net/.default" }));
conn.AccessToken = accessToken.Token;
return conn;
}