Prevent FormsAuthenticationModule of intercepting ASP.NET Web API responses

前端 未结 3 1635
一整个雨季
一整个雨季 2020-12-15 10:10

In ASP.NET the FormsAuthenticationModule intercepts any HTTP 401, and returns an HTTP 302 redirection to the login page. This is a pain for AJAX, since you ask for json and

3条回答
  •  渐次进展
    2020-12-15 10:34

    In case someone's interested in dealing with the same issue in ASP.NET MVC app using the Authorize attribute:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class Authorize2Attribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                filterContext.Result = new HttpStatusCodeResult((int) HttpStatusCode.Forbidden);
            }
            else
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
                }
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    } 
    

    This way browser properly distinguishes between Forbidden and Unauthorized requests..

提交回复
热议问题