sab*_*ber 3 .net c# asp.net asp.net-mvc fluent-security
嗨,我正在使用FluentSecurity来验证和验证我的MVC应用程序中的用户权限.在用户想要访问被拒绝的基本设置中,Action它会抛出异常.我想知道如何重定向到另一个页面(例如登录页面)而不是显示黄色异常页面?
我知道这个问题已经得到了回答,但是我不喜欢在每一个动作中都尝试一下来处理这种情况.
Fluent Security允许您注册违反策略的处理程序(请参阅https://github.com/kristofferahl/FluentSecurity/wiki/Policy-violation-handlers).您必须拥有一个继承自IPolicyViolationHandler的类.惯例是命名你的班级<PolicyViolationName>PolicyViolationHandler
以下是注册DenyAnonymousAccessPolicyViolationHandler的Handler示例
/// <summary>
/// Custom Policy Violation Handler. See http://www.fluentsecurity.net/wiki/Policy-violation-handlers
/// </summary>
public class DenyAnonymousAccessPolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
Flash.Error("You must first login to access that page");
return new RedirectResult("/");
}
}
Run Code Online (Sandbox Code Playgroud)
您将遇到的另一个警告是您必须使用IOC容器来注册这些处理程序.我不会讨论使用和IOC容器是好还是坏,但如果我没有,我宁愿不使用.在他们的网站上有一篇关于如何在不使用IOC容器的情况下写这篇文章的博客,但我也不太喜欢这种方法.这就是我做的.
public static class SecurityConfig
{
public static void Configure()
{
SecurityConfigurator.Configure(c =>
{
c.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
c.GetRolesFrom(() => (HttpContext.Current.Session["Roles"] as string[]));
// Blanked Deny All
c.ForAllControllers().DenyAnonymousAccess();
// Publicly Accessible Areas
c.For<LoginController>().Ignore();
// This is the part for finding all of the classes that inherit
// from IPolicyViolationHandler so you don't have to use an IOC
// Container.
c.ResolveServicesUsing(type =>
{
if (type == typeof (IPolicyViolationHandler))
{
var types = Assembly
.GetAssembly(typeof(MvcApplication))
.GetTypes()
.Where(x => typeof(IPolicyViolationHandler).IsAssignableFrom(x)).ToList();
var handlers = types.Select(t => Activator.CreateInstance(t) as IPolicyViolationHandler).ToList();
return handlers;
}
return Enumerable.Empty<object>();
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1587 次 |
| 最近记录: |