Search code examples
hangfire

How can I config one user has ReadOnly access and another user have full access to Hangfire Dashboard?


How can I config one user has ReadOnly access and another user have full access to Dashboard?


Solution

  • You can use the DashboardOptions and AuthorizationFilter to set up the Read-Only and Edit access. See Documentation from Hangfire

    public class HangFireAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize([NotNull] DashboardContext context)
        {
            string user = HttpContext.Current.User.Identity.Name;
            var adminAuthz = InternalMethod.lookup_db_for_user_access(user, "View");
    
            return adminAuthz != null;
        }
    
        public bool IsUserAuthorizedToEditHangfireDashboard([NotNull] DashboardContext context)
        {
            string user = HttpContext.Current.User.Identity.Name;
            var adminAuthz = InternalMethod.lookup_db_for_user_access(user, "Edit");
    
            return adminAuthz != null;
        }
    }
    

    Use the above filter in your Hangfire Dashboard initialization

    public void Configuration(IAppBuilder app)
    {
        var hangfireAuthz = new HangFireAuthorizationFilter();
        var dashboardOptions = new DashboardOptions
        {
            Authorization = new[] { hangfireAuthz },
            IsReadOnlyFunc = (DashboardContext context) => !hangfireAuthz.IsUserAuthorizedToEditHangfireDashboard(context)
        };
    
        app.UseHangfireDashboard("/hangfire", dashboardOptions);
    }