AuthorizeCore in MVC
In MVC AuthorizeAttribute Class is another cool feature that makes it easy to add authentication at the Controller level. In AuthorizeAttribute class we have AuthorizeCore function, it specifies that access to a controller or action method is restricted to users who meet the authorization requirement. We can override AuthorizeCore function as per our authorization logic.
When you place the [Authorize] attribute on a Controller’s action method, a couple of calls get made to the AuthorizeAttribute class at the beginning of each request to your controller to authenticate users. Lately when I was working on a web application I found this multiple calls as an extra overload that even though the user is authorized, AuthorizeCore got executed.
So to avoid this multiple calls, I found one of the property in HttpContext which is SkipAuthorization. SkipAuthorization is a boolean property, you can set this as true once the user is authorized. The below code snippet will give you the brief idea.
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.SkipAuthorization) return true; // hack to avoid multiple call to the method
if (!authorized) //if user is not authorize
{
return false;
}
if (authorized) //if user is authorize
{
httpContext.SkipAuthorization = true;
return true;
}
return false;
}