Thank you so much for replying. I followed your recommendations and I was able to implement a custom provider. Let me share with you the Custom Provider approach's code:
public class SqlAzureConnectionProvider : NHibernate.Connection.DriverConnectionProvider
{
private readonly NLog.Logger Logger = NLog.LogManager.GetLogger("Default");
public override DbConnection GetConnection()
{
SqlConnection connection = (SqlConnection) Driver.CreateConnection();
try
{
string accessToken = GetAccessToken();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
connection.AccessToken = accessToken;
connection.Open();
}
catch (Exception)
{
connection.Dispose();
throw;
}
//return base.GetConnection();
return connection;
}
private string GetAccessToken()
{
string accessToken;
if (System.Configuration.ConfigurationManager.AppSettings["Environment"] == "Development")
{
Logger.Info("Development - Reading credential fom web.config file");
// For local debugging it will use the AppReg credentials to generate the Access Token
string clientId = System.Configuration.ConfigurationManager.AppSettings["client_id"];
string aadTenantId = System.Configuration.ConfigurationManager.AppSettings["tenant_id"];
string clientSecretKey = System.Configuration.ConfigurationManager.AppSettings["client_secret"];
AuthenticationContext authenticationContext = new AuthenticationContext(string.Format(AadInstance, aadTenantId));
ClientCredential clientCredential = new ClientCredential(clientId, clientSecretKey);
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(ResourceId, clientCredential).Result;
accessToken = authenticationResult.AccessToken;
Logger.Info("Development - Access Token generated");
}
else
{
// On Production Release, Virtual Machine Managed Identity will be used to generate the Access Token
Logger.Info("Generating Managed Identity-based Access Token");
webRequest.Headers["Metadata"] = "true";
webRequest.Method = "GET";
try
{
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Logger.Info("Azure Instance Metadata Service REST API status code: {0}", webResponse.StatusCode);
StreamReader streamResponse = new StreamReader(webResponse.GetResponseStream());
string stringResponse = streamResponse.ReadToEnd();
JObject jsonResponse = JObject.Parse(stringResponse);
accessToken = jsonResponse["access_token"].Value<string>();
Logger.Info("Access Token generated");
}
catch (Exception exc)
{
Logger.Error(exc, "Error by generatin Access Token.");
throw;
}
}
return accessToken;
}
}
I hope this implementation can help other users...