How to override sql server connection logic to use WindowsImpersonationContext WindowsIdentity?

I don’t wish to impersonate for the entire application’s life.

For example on startup to undo the impersonation:

using (System.Security.Principal.WindowsImpersonationContext ctx = someWindowsIdentity.Impersonate())
{
GlobalConfiguration.Configuration.UseSqlServerStorage(“x”);

ctx.Undo();
}

Is there a way I can get Hangfire to go through this code everytime it establishes a connection to its SsqlServerStorage? How does Hangfire establish and mantain its connections? Is there somewhere I can override this?

Pulled Hangfire.SqlServer and added WindowsIdentity as a SqlServerStorageOptions.

Added the impersonation code to SqlServerStorage

    internal DbConnection CreateAndOpenConnection()
    {
        var connection = _existingConnection ?? new SqlConnection(_connectionString);

        if (connection.State == ConnectionState.Closed)
        {
            if (_options.WindowsIdentity != null)
            {
                using (WindowsImpersonationContext ctx = _options.WindowsIdentity.Impersonate())
                {
                    connection.Open();

                    ctx.Undo();
                }
            }
            else
            {
                connection.Open();
            }
        }

        return connection;
    }

Seems to work :slight_smile: