Hangfire icon indicating copy to clipboard operation
Hangfire copied to clipboard

Azure AD Identity with JWT Bearer Support

Open mw-nfi opened this issue 3 years ago • 2 comments

Hi, i tested hangfire with .net 6.0. All works fine. But i trying to secure the Dashboard with Azure Identity (JWT Bearer). How does it works? Here is my Program.cs. Thanks!

var builder = WebApplication.CreateBuilder(args);
const string HangfirePolicyName = "HangfirePolicy"; // Can be any name
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")).EnableTokenAcquisitionToCallDownstreamApi()
            .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
            .AddInMemoryTokenCaches();


// Add a new policy for hangfire
builder.Services.AddAuthorization(options =>
{
    // Policy to be applied to hangfire endpoint
    options.AddPolicy(HangfirePolicyName, builder =>
    {
        builder
            .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser();
    });
});




builder.Services.AddHangfireServer();
builder.Services.AddHangfire(configuration => configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseMemoryStorage());



builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseBlazorFrameworkFiles();
app.UseStaticFiles();


app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();

// Hangfire Settings
app.UseHangfireDashboard();


app.UseEndpoints(endpoints =>
{
    app.MapRazorPages();
    app.MapControllers();
    endpoints.MapHangfireDashboard("/hangfire", new DashboardOptions()
    {
        Authorization = new List<IDashboardAuthorizationFilter> { }
    })
    .RequireAuthorization(HangfirePolicyName);
});




app.MapFallbackToFile("index.html");






app.Run();

mw-nfi avatar Apr 22 '22 15:04 mw-nfi

@mw-nfi have you found a solution yet?

amz-x avatar May 12 '22 08:05 amz-x

No :/ Hangfire needs a new Authorization Handler for handling azure Identity.

About owin you could realize it but that is too old....

Is an update in planning?

mw-nfi avatar Jul 11 '22 09:07 mw-nfi

same problem here :(

Trapulo avatar Apr 05 '23 14:04 Trapulo