Search code examples
c#visual-studiomodel-view-controllerhangfire

How can I protect MVC Hangfire Dashboard


I'm using Visual Studio 2013 MVC, and I installed "Hangfire" to perform scheduled tasks. (http://hangfire.io/)

How can I protect the Web Monitoring UI page (http://localhost/Hangfire) with a password?

Thanks


Solution

  • Let me give the entire code for a RestrictiveAuthorizationFilter: This way you can handle authorization however you desire.

    Assuming you have the OWINStartup class added.

    OWINStartup.cs

    using Owin;
    using Hangfire;
    using Hangfire.Dashboard;
    
    public class OWINStartup
    {
        public void Configuration(IAppBuilder app)
        {        
            GlobalConfiguration.Configuration.UseSqlServerStorage("String");
            DashboardOptions options = new DashboardOptions()
            {
                AuthorizationFilters = new IAuthorizationFilter[]
                {
                    new MyRestrictiveAuthorizationFilter()
                }
            };
            app.UseHangfireDashboard("/hangfire", options);
        }
    }
    

    RestrictiveAuthorizationFilter.cs

    using Hangfire.Dashboard;
    using System.Collections.Generic;
    using Microsoft.Owin;
    
    public class MyRestrictiveAuthorizationFilter : IAuthorizationFilter
    {
        public bool Authorize(IDictionary<string, object> owinEnvironment)
        {
            var context = new OwinContext(owinEnvironment);
    
            return context.Authentication.User.Identity.IsAuthenticated;
        }
    }
    

    Notice: using System.Collections.Generic;

    References: https://github.com/HangfireIO/Hangfire/issues/202

    https://media.readthedocs.org/pdf/hangfire/latest/hangfire.pdf (page 20)

    Hangfire.Dashboard.Authorization version: 2.1.0