我设法在我的ASP.NET Core MVC应用程序上使用Hangfire,现在我试图添加管理员授权。
我将以下代码添加到Startup.cs文件中:
app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] {new SecurityHelpers.AdminAuthorization.HangFireAuthorizationFilter() } }); app.UseHangfireServer(); RecurringJob.AddOrUpdate( () => Debug.WriteLine("Minutely Job"), Cron.Minutely);
现在,我对自定义授权过滤器有疑问:
public class HangFireAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize(DashboardContext context) { return true; } }
有一些使用IAutohorizationFilter进行旧配置的示例,并且在版本1.6.8中,有一个新接口IDashboardAuthorizationFilter,我不知道如何实现它。
我的Web应用程序使用声明。
n
这是我对.NET Core的实现:
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter { private string policyName; public HangfireAuthorizationFilter(string policyName) { this.policyName = policyName; } public bool Authorize([NotNull] DashboardContext context) { var httpContext = context.GetHttpContext(); var authService = httpContext.RequestServices.GetRequiredService(); return authService.AuthorizeAsync(httpContext.User, this.policyName).ConfigureAwait(false).GetAwaiter().GetResult(); } }
使用以下命令进行设置Startup
Configure
:
app.UseHangfireDashboard( pathMatch: "/hangfire", options: new DashboardOptions() { Authorization = new IDashboardAuthorizationFilter[] { new HangfireAuthorizationFilter("somePolicy") } });
确保您先前选择的策略(例如“ somePolicy”)已设置Startup
ConfigureServices
。例如:
services.Configure(options => { options.AddPolicy("somePolicy", policy => { // require the user to be authenticated policy.RequireAuthenticatedUser(); // Maybe require a claim here, if you need that. //policy.RequireClaim(ClaimTypes.Role, "some role claim"); }); };