ASP.NET MVC:如何向AUTHORIZE属性添加内容

12

我如何创建一个自定义属性来扩展MVC中现有的Authorize属性?


请添加更多细节,您想要扩展什么? - Mike Chaliy
现在我只想能够重定向到正确的页面,而不是默认的主页。 - zsharp
5
你可以更新你的问题,这样每个人都能知道你需要什么。 - Mike Chaliy
4个回答

18

从AuthorizeAttribute派生你的类。重写OnAuthorization方法。添加并设置CacheValidationHandler。

public void CacheValidationHandler( HttpContext context,
                                    object data,
                                    ref HttpValidationStatus validationStatus )
{
    validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
}


public override void OnAuthorization( AuthorizationContext filterContext )
{
    if (filterContext == null)
    {
        throw new ArgumentNullException( "filterContext" );
    }

    if (AuthorizeCore( filterContext.HttpContext ))
    {
       ... your custom code ...
       SetCachePolicy( filterContext );
    }
    else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
        // auth failed, redirect to login page
        filterContext.Result = new HttpUnauthorizedResult();
    }
    else
    {
       ... handle a different case than not authenticated
    }
}


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( CacheValidationHandler, null /* data */);
 }

我该如何使用角色使其工作?现在它可以正常运行,但好像角色没有起作用。此外,即使用户已通过身份验证,AuthorizeCore仍然返回false,这意味着SetCachePolicy()永远不会被执行。 - Nick Masao
@Nick - 我已经在博客中写了关于改进缓存处理方面的文章:http://farm-fresh-code.blogspot.com/2011/03/revisiting-custom-authorization-in.html - tvanfosson

10

您不需要扩展该属性,web.config就足够了。请阅读关于身份验证的表单元素的内容。请注意defaultUrl,这是您需要的内容。

<system.web>
  <authentication mode="Forms">
    <forms defaultUrl="YourUrlGoesHere"/>
  </authentication>
</system.web>

但这不是动态的。URL会改变。 - zsharp
7
为什么不在提供解决方案之前明确所有要求呢? - Mike Chaliy
1
不对!这完全是错误的:http://blogs.msdn.com/b/rickandy/archive/2010/08/24/securing-your-mvc-application.aspx - handles
哎呀,如果该博客文章开头所做的断言是正确的,那么你应该考虑减少损失并删除答案。 - MrBoJangles

3
public class CoolAuthorizeAttribute :  AuthorizeAttribute
{
}

0

我建议如果你只想扩展当前的AuthorizeAttribute并在其上添加自己的授权,而不是覆盖OnAuthorization方法,只需重写AuthorizeCore方法并将MyCustomAuthorizationHolds条件添加到其中即可。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (base.AuthorizeCore(httpContext) && MyCustomAuthorizationHolds)
            return true;

        return false;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接