ASP.Net MVC:是否可以覆盖AuthorizeAttribute?

我当前的项目是使用ASP.Net MVC构建的内部Web应用程序,我正在添加身份validation。 我有一个预先构建的HTTPModule,它创建一个具有适当角色的IPrincipal。 如果用户未经过身份validation,我会获得一个角色为“Public”的用户对象

由于这是一个内部应用程序,因此大多数页面都是私有的,只能查看角色“Admin”。 因为我有一个基本控制器,我可以这样做:

[Authorize(Roles="Admin")] public abstract class MyControllerBase : Controller { ... } 

我有一个问题,因为有些动作可以在公共网站上查看,如果我将它们归类为:

 [Authorize(Roles="Public")] public class LoginController : MyController { public ActionResult Index() { } } 

由于未对用户进行身份validation,因此无法加载页面。 看起来“inheritance的类会忽略公共”的作用。是否有人知道角色是否可以被inheritance的类重写?

我也试图避免使用Roles =“Admin”归因于所有控制器

谢谢,基思。

您可以从AuthorizeAttribute派生新属性并覆盖OnAuthorization方法,然后应用您的自定义属性而不是授权。 下面是我的一个自定义属性的OnAuthorization方法,如果权限不足,则重定向到错误页面而不是重定向到登录页面。

不过,我不确定这会给你带来什么。 当您使用属性装饰您的类时,可能您必须同时允许Admin和Public(因此,您是谁限制,因为Public是未经过身份validation的任何人?)。 然后,您必须装饰需要单独限制为Admin的每个控制器方法,因为class属性将允许访问。 您可以使用常规的Authorize属性来实现此行为,只需修改那些非公开可用的方法(或没有公开方法的类)。

我想你可以检查属性,看看被调用的方法是否也用属性修饰,只需批准授权,这将有效地将授权推迟到方法级别。 您可能必须查看AuthorizationContext上的RouteData以获取操作并使用reflection尝试根据参数和请求类型查找适当的方法。

  public override void OnAuthorization( AuthorizationContext filterContext ) { if (filterContext == null) { throw new ArgumentNullException( "filterContext" ); } if (AuthorizeCore( filterContext.HttpContext )) { SetCachePolicy( filterContext ); } else if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // auth failed, redirect to login page filterContext.Result = new HttpUnauthorizedResult(); } else { ViewDataDictionary viewData = new ViewDataDictionary(); viewData.Add( "Message", "You do not have sufficient privileges for this operation." ); filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData }; } } protected void SetCachePolicy( AuthorizationContext filterContext ) { // ** IMPORTANT ** // Since we're performing authorization at the action level, the authorization code runs // after the output caching module. In the worst case this could allow an authorized user // to cause the page to be cached, then an unauthorized user would later be served the // cached page. We work around this by telling proxies not to cache the sensitive page, // then we hook our custom authorization code into the caching mechanism so that we have // the final say on whether a page should be served from the cache. HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) ); cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */); } 

最后,我想我的回答是在问题中。 我没有将Authorize属性放在我的基本控制器上,而是派生了一个新的AdminBaseController。

 [HandleError] public abstract class MyControllerBase : Controller { ... } [Authorize(Roles="Admin")] public abstract class AdminControllerBase : MyControllerBase { .... } 

现在,任何需要身份validation的控制器都可以从AdminControllerBase派生,而我的公共控制器可以从MyControllerBase派生。 OO来救援。