Search code examples
f#hangfiref#-giraffe

How to set Hangfire authorization in F#?


According to the Hangire Documentation, allowing authorization to Hangfire dashboard can be done in the following way in C#:

// For ASP.NET Core environments, use the GetHttpContext extension method defined in the Hangfire.AspNetCore package.

public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        var httpContext = context.GetHttpContext();

        // Allow all authenticated users to see the Dashboard (potentially dangerous).
        return httpContext.User.Identity.IsAuthenticated;
    }
}

// The second step is to pass it to the UseHangfireDashboard method. You can pass multiple filters, and the access will be granted only if all of them return true.

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

I'm using Giraffe as web server, and I've tried the following way:

type HangfireAuthorization () =
    interface IDashboardAuthorizationFilter with
        override _.Authorize (dc: DashboardContext) =
            false

type WebApp(context: StatelessServiceContext) =
    inherit StatelessService(context)
    //....

    let configureApp (app: IApplicationBuilder) =
            let storageContext = app.ApplicationServices.GetService(typeof<StorageContext>) :?> StorageContext

            let hangfireDashboardOptions: DashboardOptions =
                let x = DashboardOptions()
                x.Authorization <- HangfireAuthorization() // how to correctly set this option?
                x

            app.UseGiraffeErrorHandler(errorHandler)
               .UseCors("AllowCors")
               .UseHangfireDashboard("/hangfire", hangfireDashboardOptions)

How can I correctly set the authorization field of the Hangfire DashboardOptions?


Solution

  • I got it working like this:

    type HangfireAuthorization () =
        interface IDashboardAuthorizationFilter with
            override _.Authorize (dc: DashboardContext) =
                false 
    
     let hangfireDashboardOptions: DashboardOptions =
         let x = DashboardOptions()
         x.Authorization <- [ HangfireAuthorization() ] // or [| HangfireAuthorization() |]
         x
    
     app.UseGiraffeErrorHandler(errorHandler)
     .UseCors("AllowCors")
     .UseHangfireDashboard("/hangfire", hangfireDashboardOptions)