How do I create a custom attribute to extend existing Authorize attribute in MVC?
+8
A:
Derive your class from AuthorizeAttribute. Override the OnAuthorization method. Add and set up a 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 */);
}
tvanfosson
2009-02-16 18:34:00
ok, but how exactly can i correctly redirect to last page?
zsharp
2009-02-16 18:47:40
@tvanfosson: edit? last line: CacheValidateHandler => CacheValidationHandler
Martin
2010-03-29 11:18:50
+5
A:
You do not need to extend this attribute, web.config is enough. Please read about forms Element for authentication. Pay your attention on defaultUrl. This is something what you need.
<system.web>
<authentication mode="Forms">
<forms defaultUrl="YourUrlGoesHere"/>
</authentication>
</system.web>
Mike Chaliy
2009-02-16 19:29:59
Hm, why not to specify all requirments before one will give solution?
Mike Chaliy
2009-02-16 22:13:17
+3
A:
Check out this post for how to override the AuthorizeAttribute Class.
http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/
Schotime
2009-02-17 12:26:03
If the solution isn't contained within stackoverflow it's not that useful to those searching for it.
Jason
2010-07-16 06:43:34