2
我有一个ASP.NET MVC4站点,具有两种类型的角色:管理员和合作伙伴。ASP.NET MVC4重写OnAuthorization允许角色白名单
基本上,对网站的所有访问都需要用户进行身份验证并具有管理员角色。 因此,我这样做是FilterConfig.cs(从Global.asax中调用):
public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute { Roles = "Administrator" }); // default deny
}
}
对于一个控制器,但是我想授予与合作伙伴的角色,但wihtout其管理员角色的访问用户。我知道我可以通过不使用全局过滤器,而是在每个Controller或Action上设置Authorize属性来完成此操作,但是我希望使用白名单方法,而不是默认情况下所有acces需要“Administrator”角色,然后使用某种形式的白名单。
我一直在使用一个控制器,试图在那里我重写OnAuthorization这样的:
public class MyController : Controller {
protected override void OnAuthorization(AuthorizationContext filterContext) {
if (User.Identity.IsAuthenticated) {
var attributes = new List<AllowRolesAttribute>();
attributes.AddRange(filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AllowRolesAttribute>());
attributes.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(true).OfType<AllowRolesAttribute>());
foreach (var authorizationAttribute in attributes) {
foreach (var role in authorizationAttribute.Roles.Split(',')) {
if (User.IsInRole(role))
return; // Skip authorization because user has one of the allowed roles.
}
}
}
base.OnAuthorization(filterContext);
}
}
我再这样定义控制器:
[AllowRoles(Roles = "Partner")]
public class HomeController : MyController
{
...
但是,这是行不通的。当我与角色为“合作伙伴”的用户访问此控制器时,我可以将代码按照内部返回语句进行操作,但用户仍然被重定向到登录页面,而不是被授权。我在这里错过了什么?
是的我正在使用窗体身份验证。我希望AllowRoles属性的作用是,尽管用户没有全局需求的管理员角色,但可以为具有角色参数中给定角色的用户授予某些控制器/操作的访问权限。 –