Was*_*ter 2 asp.net-core-mvc hangfire
我设法在我的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);
Run Code Online (Sandbox Code Playgroud)
现在,我对自定义授权过滤器有疑问:
public class HangFireAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
有一些使用IAutohorizationFilter进行旧配置的示例,并且在版本1.6.8中,有一个新接口IDashboardAuthorizationFilter,我不知道如何实现它。
我的Web应用程序使用声明。
n
小智 9
在 Hangfire 中为 asp.net core 添加自定义基本身份验证
使用 Hangfire.Dashboard.Basic.Authentication nuget 包。
使用命令安装
Install-Package Hangfire.Dashboard.Basic.Authentication
Run Code Online (Sandbox Code Playgroud)
在启动配置方法中添加以下内容
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
//AppPath = "" //The path for the Back To Site link. Set to null in order to hide the Back To Site link.
DashboardTitle = "My Website",
Authorization = new[]
{
new HangfireCustomBasicAuthenticationFilter{
User = _configuration.GetSection("HangfireSettings:UserName").Value,
Pass = _configuration.GetSection("HangfireSettings:Password").Value
}
}
});
Run Code Online (Sandbox Code Playgroud)
在 appsettings.json 中添加以下内容(使用您的用户名和密码)
"HangfireSettings": {
"UserName": "admin",
"Password": "password"
}
Run Code Online (Sandbox Code Playgroud)
这是我对.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<IAuthorizationService>();
return authService.AuthorizeAsync(httpContext.User, this.policyName).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下命令进行设置Startup Configure:
app.UseHangfireDashboard(
pathMatch: "/hangfire",
options: new DashboardOptions() {
Authorization = new IDashboardAuthorizationFilter[] {
new HangfireAuthorizationFilter("somePolicy")
}
});
Run Code Online (Sandbox Code Playgroud)
确保您先前选择的策略(例如“ somePolicy”)已设置Startup ConfigureServices。例如:
services.Configure<AuthorizationOptions>(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");
});
};
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您使用 .NET Core 2.0,则需要自定义实现以符合新的身份验证标准。
您需要添加一个中间件。这个是由 HangFire 在他们的 Github 页面/问题中提供的。
public class HangfireDashboardMiddleware
{
private readonly DashboardOptions _dashboardOptions;
private readonly JobStorage _jobStorage;
private readonly RequestDelegate _nextRequestDelegate;
private readonly RouteCollection _routeCollection;
public HangfireDashboardMiddleware(
RequestDelegate nextRequestDelegate,
JobStorage storage,
DashboardOptions options,
RouteCollection routes)
{
_nextRequestDelegate = nextRequestDelegate;
_jobStorage = storage;
_dashboardOptions = options;
_routeCollection = routes;
}
public async Task Invoke(HttpContext httpContext)
{
var aspNetCoreDashboardContext =
new AspNetCoreDashboardContext(_jobStorage, _dashboardOptions, httpContext);
var findResult = _routeCollection.FindDispatcher(httpContext.Request.Path.Value);
if (findResult == null)
{
await _nextRequestDelegate.Invoke(httpContext);
return;
}
// attempt to authenticate against default auth scheme (this will attempt to authenticate using data in request, but doesn't send challenge)
var result = await httpContext.AuthenticateAsync();
if (!httpContext.User.Identity.IsAuthenticated)
{
// request was not authenticated, send challenge and do not continue processing this request
await httpContext.ChallengeAsync();
}
if (_dashboardOptions
.Authorization
.Any(filter =>
filter.Authorize(aspNetCoreDashboardContext) == false))
{
var isAuthenticated = httpContext.User?.Identity?.IsAuthenticated;
httpContext.Response.StatusCode = isAuthenticated == true
? (int) HttpStatusCode.Forbidden
: (int) HttpStatusCode.Unauthorized;
return;
}
aspNetCoreDashboardContext.UriMatch = findResult.Item2;
await findResult.Item1.Dispatch(aspNetCoreDashboardContext);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的 Startup.cs 中你需要添加这个方法
private static IApplicationBuilder UseHangfireDashboardCustom(IApplicationBuilder app,string pathMatch = "/hangfire",DashboardOptions options = null,JobStorage storage = null)
{
var services = app.ApplicationServices;
storage = storage ?? services.GetRequiredService<JobStorage>();
options = options ?? services.GetService<DashboardOptions>() ?? new DashboardOptions();
var routes = app.ApplicationServices.GetRequiredService<RouteCollection>();
app.Map(new PathString(pathMatch), x =>
x.UseMiddleware<HangfireDashboardMiddleware>(storage, options, routes));
return app;
}
Run Code Online (Sandbox Code Playgroud)
最后,使用自定义授权
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes => routes.MapRoute(
"default",
"{controller=Home}/{action=Index}/{id?}"));
app.UseHangfireServer();
//Voila!
UseHangfireDashboardCustom(app);
}
Run Code Online (Sandbox Code Playgroud)
这就是我的实现方式IDashboardAuthorizationFilter
public class HangfireAuthorizeFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var owinEnvironment = context.GetOwinEnvironment();
if (owinEnvironment.ContainsKey("server.User"))
{
if (owinEnvironment["server.User"] is ClaimsPrincipal)
{
return (owinEnvironment["server.User"] as ClaimsPrincipal).Identity.IsAuthenticated;
}
else if (owinEnvironment["server.User"] is GenericPrincipal)
{
return (owinEnvironment["server.User"] as GenericPrincipal).Identity.IsAuthenticated;
}
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
在你的启动中
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new [] { new HangfireAuthorizeFilter() }
});
Run Code Online (Sandbox Code Playgroud)