I’m trying to do some custom authorization so I created a controller overriding the OnAuthorization method. I also applied the Authorize attribute to this controller.
The question is why is the OnAuthorization method called BEFORE the basic forms authentication process?
I would like to authorize the user after he is authenticated.
Am I missing something?
Here is the code:
[Authorize]
public class AuthorizationController : Controller
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
List<string> allowedControllers = new List<string>() { "SecurityController" };
List<string> allowedActions = new List<string>() { "Index" };
string controllerName = filterContext.Controller.GetType().Name;
string actionName = filterContext.ActionDescriptor.ActionName;
if (!allowedControllers.Contains(controllerName)
|| !allowedActions.Contains(actionName))
{
filterContext.Result = View("UnauthorizedAccess");
}
}
}
The controller that I tested with is something like:
public class SecurityController : AuthorizationController
{
public ActionResult Index()
{
return View();
}
public ActionResult AnotherIndex()
{
return View();
}
}
One of the first things the
AuthorizeAttributedoes is check to see if the user is authenticated. If they are not then that is when a redirect to the login page will be issued.The
AuthorizeAttributebasically wraps the authentication check in with the authorization piece:When you use the AuthorizeAttribute with no roles/users as you do in your example ([Authorize]), it is basically just checking to make sure the user is authenticated in this case.
I would probably change your code to override the AuthorizeAttribute instead of doing this code in your controller. You can do the following: