outputcaching with authorize filter

. Wednesday, May 4, 2011
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks


Hi guys,after a long time I am back to blogging,today I am going to explain about how to use outputcaching with authorizefilter.

for outputcaching you can refer by previous blog.
(outputcaching is also a kind of filter)

Filters in asp.net mvc : 

Authorize filter
Raises before any action execute and authorize the current user.
Action filter
two method overridden from actionfilterattribute class
onactionexecuting : before action get executed.
onactionexecuted : after action get executed.
Result Filter
two method overriden from actionfilterattribute class
onresultexecuting : before result get executed,
eg: when you return view() from any action this method executed before this.
onresultexecuted : after result get executed.

Exception filter
whenever action throws any exception.
class for this filter is HandleErrorAttribute.

Note: controller inherited from controllerbase class in which it implements filter attribute so ultimately your controller can also implement these attributes.
Eg:

[Athorize]
your action..

Using outputcaching with Authorize filter :

Problem : 

if we use both of these filters in the worst case the unauthorize users even can view the cached content of authorize users,to avoid we need to use a custom class which

implements authorizefilterattribute class.

public class EnhancedAuthorizeAttribute : AuthorizeAttribute
{
public bool AlwaysAllowLocalRequests = false;
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
if (AlwaysAllowLocalRequests && httpContext.Request.IsLocal)
return true;
// Fall back on normal [Authorize] behavior
return base.AuthorizeCore(httpContext);
}
}

[EnhancedAuthorize(Roles = "admin", AlwaysAllowLocalRequests = true)]
Now, this will grant login only for admin roles and not to any other role.

but I achieve this wtih athorize attribute

eg:
 [Authorize(Roles="admin")]
 [OutputCache(Duration=30,VaryByParam="None")]

note : order is a property of filter base class which defines the order of filter execution but by default filter are put on stack for execution which means the last one will be executed first.

0 comments: