Browse Source

Hangfire Dashboard Authorization In API Website.

pull/20704/head
maliming 1 year ago
parent
commit
09e9825fb4
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 69
      docs/en/framework/infrastructure/background-jobs/hangfire.md

69
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<bool>("AuthServer:RequireHttpsMetadata");
options.Audience = "MyProjectName";
});
context.Services.AddAuthentication()
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.RequireHttpsMetadata = configuration.GetValue<bool>("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()};
});
```
Loading…
Cancel
Save