HangfireIO / Hangfire

An easy way to perform background job processing in .NET and .NET Core applications. No Windows Service or separate process required
https://www.hangfire.io
Other
9.41k stars 1.7k forks source link

Azure AD Identity with JWT Bearer Support #2027

Open mw-nfi opened 2 years ago

mw-nfi commented 2 years ago

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();
amz-x commented 2 years ago

@mw-nfi have you found a solution yet?

mw-nfi commented 2 years ago

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?

Trapulo commented 1 year ago

same problem here :(