Using Hangfire with Azure and Managed Identity

sql-azure
Tags: #<Tag:0x00007f49a6dbaff0>

#1

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("https://database.windows.net/").Result;
            return conn;
        }

Is this the best way to do this?