I have a utility application that is deployed to our test environments to help our developers assess the state of the platform; to do this it needs to access our Azure SQL db.
To connect to the database I'm using Authentication=Active Directory Interactive;
in the connection string; under this method when the user opens the application and begins the connection process they are presented with an Azure AD authentication dialog and they can log in with their AD credentials via two factor auth.
This all works fine except for the fact that, if the user leaves the application for a few minutes (or otherwise doesn't do anything that causes a SQL query to be performed), they will then be prompted for another authentication dialog where they have to go through the entire login process again, 2FA and all. It's like the authentication 'expires'.
At the moment I'm leaving the application deployed as it is because it does work, but its users (myself included) are being driven mad by the need to constantly log in.
In an attempt to stop the authentication from expiring I've tried putting a simple select 1
query on a loop in the background (see the following code snippet) but this didn't work.
public SqlConnection GetSqlConnection()
{
if (_connectionString is null)
{
throw new InvalidOperationException(
"The connection string has not been set");
}
if (_sqlConnection is not null)
{
return _sqlConnection;
}
_sqlConnection = new SqlConnection(_connectionString);
if (_keepAlive)
{
_keepAliveTimer =
new Timer(_keepAliveTickLength) { AutoReset = true, Enabled = true };
_keepAliveTimer.Elapsed += (_, _) =>
{
_sqlConnection?.Query("select 1");
};
}
return _sqlConnection;
}
I have to admit my understanding of how AD authentication works in a .NET app is not very deep, so I welcome any pointers. If anyone has any ideas on how I can stop this app from needing to reauthenticate every few minutes I'd be very grateful!
In case it matters this is a .NET 5 WPF app.