The default Authorize
attribute behaves in such a way that when the user is not authenticated or authenticated but not authorized then it set the status code as 401 (UnAuthorized). When the filter sets the status code as 401 the ASP.NET framework checks if the website has forms authentication enabled and if it is then redirects to loginUrl
parameter set up there.
If you want to change that behavior say you want to redirect the user to an AccessDenied
controller if the user is authenticated but not authorized then you have to extend the Authorize
attribute and override the HandleUnauthorizedRequest
method.
For ex.
public class CustomAuthorize: AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "AccessDenied" }));
}
}
}
You can override the HandleUnauthorizedRequest
as per your need and then you have to mark the controller actions to use the CustomAuthorize
attribute instead of the built-in one.