2

I have a custom authorize attribute on my controllers and it is not being called on expired ajax requests. I'm using forms authentication, and call controller methods via $.ajax (jQuery). The ajax request returns my login page and I don't seem to be able to intercept this.

Thank you.

UPDATE: I figured out why: I commented the authorization section in my web.config like follows:

  <authentication mode="Forms">
      <forms loginUrl="/Login" timeout="1" slidingExpiration="false"/>
    </authentication>
    <!--<authorization>
      <deny users="?"/>
    </authorization>-->

Now my authorization filter is being called even after expiration. Turns out that Web.config authorization rules take precedence over Authorize filters.

Valentin V
  • 24,971
  • 33
  • 103
  • 152
  • I spent three hours racking my brain on this one. Didn't even think about commenting out the code. Worked great for MVC 5. – BeanFlicker Oct 22 '15 at 17:46

3 Answers3

4

Don't return 401 unauthorized. ASP.NET intercepts that and redirects to the login page defined in web.config. For AJAX, instead return something else, like 403.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
1

There is also a good blog on this over here:

https://www.trycatchfail.com/2011/01/17/handling-authorization-failures-for-ajax-requests-in-asp-net-mvc-applications/

TombMedia
  • 1,962
  • 2
  • 22
  • 27
Mike
  • 1,405
  • 1
  • 17
  • 27
0

Use context.HttpContext.Request.IsAjaxRequest() to detect if request is an Ajax request or not. Check more here:

Authorize attribute and jquery AJAX in asp.net MVC

Community
  • 1
  • 1
Amit M
  • 1