Wednesday, June 7, 2023

Resolve Http Status Code 200 for XHR Ajax request with HttpResponseMessage 401 Unauthorised

 Problem Statement:

Sitecore Asp.net application .net framework 4.8, there is an event on the page called by angularjs or any client side scripting to call Sitecore API controller action. Session timeout with absolute cookie expiry using Azure AD B2C Owin OpenID connect in place. After a session timeout , for any ajax call to sitecore API become non responsive , no action method called. It resulted in 200 HttpStatus code but fail to redirect to login page for customer to login again.

Request URL:http://localhost:31757/api/accountapi/login Request Method:POST Status Code:200 OK and X-Responded-JSON:{"status":401,"headers":{"location":"http:\/\/localhost:31757\/Account\/Login?ReturnUrl=%2Fapi%2Faccountapi%2Flogin"}}


 


protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (User.Identity.IsAuthenticated == false)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {

                    IServiceResponse response = new ServiceResponse();
      
                    response.Status = ServiceResponseStatuses.Redirect;
                    var uiResponse = new UiServiceResponse(string.Empty)
                    {
                        Status = ServiceResponseStatuses.Redirect,
                        RedirectUrl = "/login"
                    };
                    filterContext.Result = new JsonResult
                    {
                        Data = uiResponse,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                    return;
                }
            }
            else
                base.OnAuthorization(filterContext);
        }


No comments :