当前位置:  开发笔记 > 后端 > 正文

ASP.NET Core MVC Hangfire自定义身份验证

如何解决《ASP.NETCoreMVCHangfire自定义身份验证》经验,为你挑选了1个好方法。

我设法在我的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



1> Ryan..:

这是我对.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");
    });
};

推荐阅读
Chloemw
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有