我们是否可以将试图浏览hangfire url的用户重定向到某个未经授权的页面。我使用的是ASP.net MVC5。在我的startup.cs文件中有以下页面。
public void Configuration(IAppBuilder app)
{
String conn = System.Configuration.ConfigurationManager.
ConnectionStrings["conn"].ConnectionString;
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
GlobalConfiguration.Configuration
.UseSqlServerStorage(conn,
new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) });
//BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!"));
//app.UseHangfireDashboard();
app.UseHangfireDashboard("/Admin/hangfire", new DashboardOptions
{
Authorization =new[] { new DashboardAuthorizationFilter() }
});
//app.MapHangfireDashboard("/hangfire", new[] { new AuthorizationFilter() });
app.UseHangfireServer();
//start hangfire recurring jobs
HangFireServices service = new HangFireServices();
//service.StartArchive();
service.StartDelete();
}HangFireServices具有以下作业:
public void StartDelete()
{
List<KeyValuePair<string, int>> c = _service.GetServiceRetention();
foreach (var obj in c)
{
RecurringJob.AddOrUpdate(DELETE_SERVICE + obj.Key, () =>
Delete(obj.Key), //this is my function that does the actual process
Cron.DayInterval(Convert.ToInt32(obj.Value)));
}
}授权码为:
public class DashboardAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
//TODO:Implement
return false;
}
}默认页面是在其上设置了不同授权类的主页。用户未通过数据库的授权规则,并被重定向至UnAuthorizedController索引页。如果用户手动将url更改为指向/hangfire,因为返回的授权为假,它会看到一个空白页面,但我希望重定向到UnAuthorizedController索引页。
发布于 2017-08-18 07:08:02
如果您想要重定向到控制器上的特定页面,那么这可能会有所帮助。
我创建了一个帐户控制器,登录方法如下:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl = "jobs")
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.UserName);
await SignInManager.SignInAsync(user, false, false);
var virtualDirectory = Request.ApplicationPath.Equals("/") ? "/" : Request.ApplicationPath + "/";
return Redirect(virtualDirectory + returnUrl);
}
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}在我的Startup.Auth.cs中,我做了以下更改:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>
(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>
(ApplicationSignInManager.Create);
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
CookieName = "TestService",
LoginPath = new PathString("/Account/Login"),
SlidingExpiration = true,
ExpireTimeSpan = TimeSpan.FromMinutes(20000),
Provider = new CookieAuthenticationProvider()
});
}最后,在startup.cs类中:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
LogProvider.SetCurrentLogProvider(new HangfireLogProvider());
GlobalConfiguration.Configuration.UseSqlServerStorage("HangfirePersistence");
app.UseHangfireDashboard("/jobs", new DashboardOptions
{
Authorization = new[] { new HangfireAuthFilter() }
});
app.UseHangfireServer();
ConfigureAuth(app);
}
}
public class HangfireAuthFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var user = HttpContext.Current.User;
return user != null && user.IsInRole("Admin") && user.Identity.IsAuthenticated;
}
}当您未通过身份验证时,您将被重定向至帐户控制器上的登录操作。
发布于 2021-01-12 00:58:12
如果错误页面表示静态内容-很简单:
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize([NotNull] DashboardContext context)
{
var path = context.GetHttpContext().Request.Path;
var isResource = path != null && (path.Value.StartsWith("/css") || path.Value.StartsWith("/js") || path.Value.StartsWith("/font"));
if (!context.GetHttpContext().User.Identity.IsAuthenticated && !isResource)
{
context.Response.ContentType = "text/html";
context.Response.WriteAsync(new AccessDeniedPage().ToString(context.GetHttpContext()));
return false;
}
return true;
}
}请注意,此AccessDeniedPage不是从Hangfire.Dashboard.RazorPage继承的。原因是你不能将当前的context分配给这样的页面(Hangfire已经将它的一些功能internal)。但是如果你需要继承Microsoft.AspNetCore.Mvc.Razor.RazorPage,它看起来会像这样:
context.Response.WriteAsync(new AccessDeniedPage().ToString(context.GetHttpContext()));其中,ToString是:
public abstract class PageBase : RazorPage
{
public UrlHelper Url { get; set; }
public override async Task ExecuteAsync()
{
await Task.CompletedTask;
}
public abstract void Execute();
public string ToString(HttpContext httpContext)
{
using var output = new StringWriter();
ViewContext = new Microsoft.AspNetCore.Mvc.Rendering.ViewContext()
{
HttpContext = httpContext,
Writer = output
};
HtmlEncoder = HtmlEncoder.Default;
Url = new UrlHelper(new ActionContext
{
HttpContext = httpContext,
ActionDescriptor = new ActionDescriptor(),
RouteData = new RouteData()
});
Execute();
return output.ToString();
}https://stackoverflow.com/questions/43238816
复制相似问题