diff --git a/docs/en/framework/infrastructure/background-jobs/hangfire.md b/docs/en/framework/infrastructure/background-jobs/hangfire.md index 8d5a76509b..af112f8fec 100644 --- a/docs/en/framework/infrastructure/background-jobs/hangfire.md +++ b/docs/en/framework/infrastructure/background-jobs/hangfire.md @@ -154,3 +154,72 @@ app.UseAbpHangfireDashboard("/hangfire", options => **Important**: `UseAbpHangfireDashboard` should be called after the authentication and authorization middlewares in your `Startup` class (probably at the last line). Otherwise, authorization will always fail! + +#### Dashboard Authorization In API Website. + +If you use the hangfire dashboard in a api project that uses non-cookie authentication (like JWT Bearers), The `/hangfire` page can't authenticate the user. + +In this case, you can add a cookies authorization scheme to authenticate the user. The best way to do this is to use the `Cookie` and `OpenIdConnect` authentication schemes. This requires creating a new OAuth2 client and add the `ClientId`, `ClientSecret` properties to the `AuthServer` section in the `appsettings.json` file. + +The final code should look like below: + +```csharp +private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration) +{ + context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddAbpJwtBearer(options => + { + options.Authority = configuration["AuthServer:Authority"]; + options.RequireHttpsMetadata = configuration.GetValue("AuthServer:RequireHttpsMetadata"); + options.Audience = "MyProjectName"; + }); + + context.Services.AddAuthentication() + .AddCookie("Cookies") + .AddOpenIdConnect("oidc", options => + { + options.Authority = configuration["AuthServer:Authority"]; + options.RequireHttpsMetadata = configuration.GetValue("AuthServer:RequireHttpsMetadata"); + options.ResponseType = OpenIdConnectResponseType.CodeIdToken; + + options.ClientId = configuration["AuthServer:ClientId"]; + options.ClientSecret = configuration["AuthServer:ClientSecret"]; + + options.UsePkce = true; + options.SaveTokens = true; + options.GetClaimsFromUserInfoEndpoint = true; + + options.Scope.Add("roles"); + options.Scope.Add("email"); + options.Scope.Add("phone"); + options.Scope.Add("MyProjectName"); + }); +} +``` + +```csharp +app.Use(async (httpContext, next) => +{ + if (httpContext.Request.Path.StartsWithSegments("/hangfire")) + { + var result = await httpContext.AuthenticateAsync("Cookies"); + if (result.Succeeded) + { + httpContext.User = result.Principal; + await next(httpContext); + return; + } + + await httpContext.ChallengeAsync("oidc"); + } + else + { + await next(httpContext); + } +}); + +app.UseAbpHangfireDashboard("/hangfire", options => +{ + options.AsyncAuthorization = new[] {new AbpHangfireAuthorizationFilter()}; +}); +``` \ No newline at end of file