Custom Authorize attribute not working on expired ajax requests
I have a custom authorize attribute on my controllers and it is not being called on expired ajax requests. I'm using forms authentication, a开发者_开发百科nd 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.
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.
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/
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
精彩评论