Setup (using MVC 4)
public class MyAuthorizeAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(HttpContextBase httpContext) {
var isAuthorised = base.AuthorizeCore(httpContext);
if(isAuthorised) {
// retrieve authentication ticket from cookie and
// create custome principal and attach to
// httpContext.User
}
return isAuthorised;
}
}
Gloabl.asax.cs:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new MyAuthorizeAttribute());
}
HomeController.cs:
using System.Web.Mvc;
public class HomeController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
}
Problem
A call to the home page forces the login page to load.
Question
When the HomeController.Index() action is decorated with [AllowAnonymous], why does ASP redirect me to the login view ?
I am using this article for reference
Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action. You can apply the filter globally, at the controller level, or at the level of individual actions.
The AllowAnonymous attribute in MVC is used to skip the authorization which is enforced by Authorization Filter in MVC. Now, run the application and navigate to /Home/NonSecured and you will see that it displays the page as expected and when you navigate to /Home/Secured, then it will redirect you to the Login page.
[AllowAnonymous] bypasses all authorization statements. If you combine [AllowAnonymous] and any [Authorize] attribute, the [Authorize] attributes are ignored. For example if you apply [AllowAnonymous] at the controller level, any [Authorize] attributes on the same controller (or on any action within it) are ignored.
As per my comment on the original question. Problem was index view was calling actions on other controllers that returned partial views. Just a case of going through everything and stripping out the old [Authorize] attribute.
Although the original poster has found the cause in his case, I would like to share my resolution, as I came across this question when faced with the same symptoms.
In my web.config file I had, obeying the logic of webforms:
<authorization>
<deny users="?" />
</authorization>
You must not have this, as it will prevent the request from executing any action without logging in first, except for the login action to which the redirection takes place. I only discovered this when I tried to add a second public action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With