Using Hangfire with Azure and Managed Identity

Tags: #<Tag:0x00007faffe4ca5a8>

Hi, I’m setting up my app to run in Azure App Service and using Azure SQL for the database. I’m using a managed identity for my app service and am using that to authenticate to SQL.

My app uses EF and I have used the tutorial here to use the managed identity to connect to SQL.

For Hangfire, version 1.6.22 added functionality for connecting to sql via managed identity by adding a Connection factory overload for the SqlServerStorage class - release notes

I got it working by doing the following in startup.cs

services.AddHangfire(config =>
                    config.UseSqlServerStorage(sqlConn, new SqlServerStorageOptions
                        UseRecommendedIsolationLevel = true

        static SqlConnection sqlConn()
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.ConnectionString = "connectionString";
            SqlConnection conn = new SqlConnection(builder.ConnectionString);
            conn.AccessToken = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider().GetAccessTokenAsync("").Result;
            return conn;

Is this the best way to do this?

I am tried code in ASP.NET Core 3.1. When try to run project it’s immediately throwing
500.33 ANCM Request Handler Load Failure error.

Without above code, project is working fine. I appreciate if you can help to resolve.

For visibility, I’m here today to look into the same; Running HF as an ASP.NET app running under a user-assigned managed identity and connecting to Azure SQL database.

The connection string I tried to use causing it to throw an exception complaining about the ‘authentication’ keyword. Started doing my homework and learning about the ins & outs of this model plus the fact there’s the SqlClient v2 vs v3 to take into consideration.

So far, the closest thing to a ‘fix’ I’m seeing is the connection factory approach so you can use the access token. This would then allow us to use the ‘default’ provider which would work for both running hosted under the identity as well as local development and use of interactive/MFA credentials, etc.

For me, this seems like something HF could be seeking to make a much smoother path as it seems like it would be becoming somewhat of the predominant deployment model? Documentation + the AccessToken support perhaps would go a long ways?