以下是我的设置方法,希望对您有所帮助:
在 App_Start/NinjectWebCommon.cs 我绑定策略处理程序:
kernel.Bind<IPolicyViolationHandler>().To<DenyAnonymousAccessPolicyViolationHandler>();
kernel.Bind<IPolicyViolationHandler>().To<RequireRolePolicyViolationHandler>();
我还像这样配置 Fluent Security(使用 Ninject 服务定位器):
var locator = new NinjectServiceLocator(kernel);
ServiceLocator.SetLocatorProvider(() => locator);
SecurityConfigurator.Configure(
configuration =>
{
configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
configuration.GetRolesFrom(SecurityHelpers.UserRoles);
//HomeController and other configurations
configuration.For<HomeController>().Ignore();
configuration.ResolveServicesUsing(ServiceLocator.Current.GetAllInstances);
}
);
GlobalFilters.Filters.Add(new HandleSecurityAttribute(), 0);
然后对于每个策略,我都有一个 IPolicyViolationHandler 的实现
public class RequireRolePolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
//Make sure you're redirecting to the desired page here. You should put a stop here to debug it and see if it's being hit.
return new HttpUnauthorizedResult(exception.Message);
}
}
我有一个使用自定义成员/角色提供者和 Fluent Security 的有效解决方案。我发布了我认为是核心配置的内容。希望这可以帮助。
编辑:添加了如何获取角色。
public static class SecurityHelpers
{
public static IEnumerable<object> UserRoles()
{
var currentUser = HttpContext.Current.User.Identity.Name;
var roles = Roles.Providers["MemberAccountRoleProvider"]; //Custom Role Provider Name
return currentUser != null ? roles.GetRolesForUser(currentUser).Cast<object>().ToArray() : null;
}
}
编辑 2:我查看了您的代码,它工作正常。将此添加到您的代码中,以便您可以重定向到您想要的位置。现在你只是返回一个 Http 结果:
public class RequireRolePolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
//return new HttpUnauthorizedResult(exception.Message);
return
new RedirectToRouteResult(
new RouteValueDictionary(new { action = "Test", controller = "Account"})); //Created a view for testing
}
}
当我尝试获取设置页面时,我点击了 RequireRolePolicyViolationHandler。