0

Using Sitecore 9.1 and SXA 1.8

Does anyone know the best way to force Sitecore to return a legit 403 error when an Ajax call is hitting an API method?

Currently when the following code is thrown within the API method, Sitecore is redirecting to the /login page - so the Ajax call is getting the raw HTML of the login page sent to it with a 200 status instead of a 403 status.

throw new WebException("Invalid Credentials", WebExceptionStatus.RequestProhibitedByProxy);
0

First Approach(Recommended)

If you want to make centralizer authentication/authorization logic for any API methods then implement authentication/authorization filter, Here below sample example we are implementing custom authorization filter.

    /// <summary>
    /// CustomAuthorizationAttribute
    /// </summary>
    /// <seealso cref="System.Web.Mvc.AuthorizeAttribute" />
    public class CustomAuthorizationAttribute : AuthorizeAttribute
    {
       public override void OnAuthorization(HttpActionContext actionContext)
       {
         // Here your core logic
       }       

        /// <summary>
        /// Handles the unauthorized request.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //set unauthorized(401) response
            filterContext.Result = new HttpUnauthorizedResult(); 
        }
    }

Second Approach

As per your query, you can check response content-type using global ajaxComplete method.

$(document).ajaxComplete(function (event, request, settings) {    
    try {
        //html response and login page. 
        if (request.getResponseHeader("content-type").indexOf('html') > -1)
            //write custom logic
    }
    catch (e) {

    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.