来自DataContext的Hangfire身份验证

时间:2018-07-30 19:07:33

标签: c# asp.net-core hangfire

我正在尝试设置Hangfire,以便只有Admin用户才能访问仪表板。我的User模型具有属性UserRole,我可以将其与父枚举进行比较。

但是,我对如何从Startup.cs内将DataContext传递到Authorization过滤器感到困惑。

我应该尝试使用User对象吗?

(我正在使用实体框架)


Startup.cs

public void Configure(IApplication app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseHangfireDashboard("/hangfire", new DashboardOptions()
        {
            //ERROR here because I'm not passing in DataContext,
            //but I'm not sure how to do that...
            Authorization = new [] { new HangfireAuthorizationFilter() }
        });

        app.UseHangfireServer();
    ...
}

public class HangfireAuthorizationFilter : Controller, IDashboardAuthorizationFilter
{
    private readonly DataContext _context;

    public HangfireAuthorizationFilter(DataContext context)
    {
        _context = context;
    }

    public bool Authorize([NotNull] DashboardContext context)
    {
        var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

        try {
            var userFromRepo = _context.Users.First(u => u.Id == currentUserId);
            return userFromRepo.UserRole == UserRole.Admin;
        catch {
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是我的设置方式:

public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        if (context.GetHttpContext().User.Identity.IsAuthenticated 
              && context.GetHttpContext().User.IsInRole("admin"))
        {
            return true;
        }
        return false;
    }
}

当然,您可以用UserRole.Admin.ToString()替换字符串“ admin”