ASP.net MVC global Authorize filter forcing login

2020-03-12 03:20发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

I had similar problem and in the end I've used wrong AllowAnonymousAttribute class. There are two AllowAnonymousAttribute classes:

  • one from System.Web.Http namespace
  • another one from System.Web.Mvc namespace

In your case you have to use of course the one from System.Web.Mvc :)

I've spend more then one hour to figure it out in my program



回答4:

Though this not an answer but..

Try with the built-in Authorize code and make sure AllowAnonymous is working fine. I see in your custom authorize comments you are trying to

retrieve authentication ticket from cookie and create custome principal and attach to httpContext.User

I would suggest you do that process very earlier in the Application_AuthenticateRequest of Global.asax.cs as specified in this thread.