ASP.net MVC global Authorize filter forcing login on an AllowAnonymous action

假如想象 提交于 2019-12-30 08:13:43

问题


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.



来源:https://stackoverflow.com/questions/11033357/asp-net-mvc-global-authorize-filter-forcing-login-on-an-allowanonymous-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!