ASP.NET Core MVC Hangfire custom authentication

Wasyster picture Wasyster · Jan 12, 2017 · Viewed 8.6k times · Source

I managed to work Hangfire on my ASP.NET Core MVC application, and now I am trying to add admin authorization.

I added the following code to the Startup.cs file:

app.UseHangfireDashboard("/hangfire", new DashboardOptions
 {
    Authorization = new[] {new  SecurityHelpers.AdminAuthorization.HangFireAuthorizationFilter() }
 });

app.UseHangfireServer();
RecurringJob.AddOrUpdate( () => Debug.WriteLine("Minutely Job"), Cron.Minutely);

Now I have a problem with custom authorization filter:

public class HangFireAuthorizationFilter : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        return true;
    }
}

There are samples for old configuration with IAutohorizationFilter, and form version 1.6.8 there is a new interface IDashboardAuthorizationFilter, and I can't figure out how to implement it.

My web application uses claims.

thnx

Answer

Ryan picture Ryan · Mar 9, 2017

Here's my implementation for .NET Core:

public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter {
    private string policyName;

    public HangfireAuthorizationFilter(string policyName) {
        this.policyName = policyName;
    }

    public bool Authorize([NotNull] DashboardContext context) {
        var httpContext = context.GetHttpContext();
        var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();
        return authService.AuthorizeAsync(httpContext.User, this.policyName).ConfigureAwait(false).GetAwaiter().GetResult().Succeeded;
    }
}

Set it up in the Startup Configure with:

app.UseHangfireDashboard(
            pathMatch: "/hangfire",
            options: new DashboardOptions() {
                Authorization = new IDashboardAuthorizationFilter[] {
                    new HangfireAuthorizationFilter("somePolicy")
                }
            });

Make sure that the policy you've chosen (eg. "somePolicy") is set up previously in Startup ConfigureServices. For example:

services.Configure<AuthorizationOptions>(options => {
    options.AddPolicy("somePolicy", policy => {
        // require the user to be authenticated
        policy.RequireAuthenticatedUser();
        // Maybe require a claim here, if you need that.
        //policy.RequireClaim(ClaimTypes.Role, "some role claim");
    });
});