Securing Your Hangfire Dashboard in ASP.NET Core 8: Adding an Authorization Filter
Tags: webdev, aspdotnet, hangfire, api
Published: 2024-07-06 07:01:12

## Introduction
In our previous blog post, we explored a step-by-step guide to scheduling API calls with Hangfire in ASP.NET Core. Now, we’ll enhance our application by adding an authorization filter to secure the Hangfire dashboard. This guide will walk you through implementing an authorization filter that ensures only authenticated users can access the Hangfire dashboard.

## Adding Authorization Filter to Hangfire Dashboard
To restrict access to the Hangfire dashboard, create a custom authorization filter.

- Create a custom authorization filter class:

```
using Hangfire.Dashboard;
using Microsoft.AspNetCore.Http;
public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        var httpContext = context.GetHttpContext();
        return httpContext.User.Identity.IsAuthenticated;
    }
}
```

> **Explanation**:
> - MyAuthorizationFilter class implements the IDashboardAuthorizationFilter interface provided by Hangfire.
> - The Authorize method checks if the user is authenticated by accessing the HttpContext through context.GetHttpContext().
> - It returns true if the user is authenticated (httpContext.User.Identity.IsAuthenticated), allowing access to the Hangfire dashboard; otherwise, it returns false, denying access.

- Update the Program.cs to include the custom authorization filter:

```
using Hangfire;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
builder.Services.AddHangfire(config => 
    config.UseSqlServerStorage(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddHangfireServer();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
    Authorization = new[] { new MyAuthorizationFilter() }
});
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
```

> **Explanation**:
> - builder.Services.AddHangfire (config => config. UseSqlServerStorage (builder.Configuration. GetConnectionString (“DefaultConnection”))) configures Hangfire to use SQL Server for job storage.
> - builder.Services.AddHangfireServer() adds Hangfire’s background processing server to the services collection.
> - app.UseHangfireDashboard(“/hangfire”, new DashboardOptions { Authorization = new[] { new MyAuthorizationFilter() } }) configures the Hangfire dashboard to use the custom authorization filter we created earlier.
> - The Authorization property of DashboardOptions is set to an array containing an instance of MyAuthorizationFilter, ensuring that only authenticated users can access the Hangfire dashboard.

## Conclusion
By following this guide, you have successfully added an authorization filter to secure the Hangfire dashboard in your ASP.NET Core 8 application. This setup ensures that only logged-in users can access sensitive scheduling data, enhancing the security of your application.