Api with 401 status returning login page

550 Views Asked by At

I have created a POST API under UmbracoApiController.

    [HttpPost]
    [ActionName("SaveData")]       
    public HttpResponseMessage SaveData([FromBody]JObject data)
    {
      if (!authorized)
        {             
            return Request.CreateResponse(HttpStatusCode.Unauthorized, 
                      "Unauthorized access. Please check your credentials");
        }
    }

Instead of returning 401, it is going to the login page with 302 status.

I have created a custom attribute as well -

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class BasicAuthorization : AuthorizationFilterAttribute
{
    private const string _authorizedToken = "Authorization";

    public override void OnAuthorization(HttpActionContext filterContext)
    {
        var authorizedToken = string.Empty;

        try
        {
            var headerToken = filterContext.Request.Headers.FirstOrDefault(x => x.Key == _authorizedToken);
            if (headerToken.Key != null)
            {
                authorizedToken = Convert.ToString(headerToken.Value.SingleOrDefault());
                if (!IsAuthorize(authorizedToken))
                {
                    var httpContext = HttpContext.Current;
                    var httpResponse = httpContext.Response;

                    filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = new StringContent("Unauthorized access. Please check your credentials")
                    };

                    httpResponse.StatusCode = (int) HttpStatusCode.Unauthorized;
                    httpResponse.SuppressFormsAuthenticationRedirect = true;
                    return;
                }                    
            }
            else
            {
                filterContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
                return;
            }
        }
        catch (Exception)
        {
            filterContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
            return;
        }

        base.OnAuthorization(filterContext);
    }

    private static bool IsAuthorize(string authorizedToken)
    {
        return authorizedToken == ConfigurationManager.AppSettings["VideoIngestionKey"];
    }
}

But this also does not work. I am using Umbraco 7.6.13

Any help greatly appreciated.

Thanks

1

There are 1 best solutions below

1
On

Have something similar but used with Surface Controller not Web API controller.

Override HandleUnauthorizedRequest to implement custom response / override Umbraco & .NET defaults.

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // example redirects to a 'Forbidden' doctype/view with Reponse.StatusCode set in view; 
        filterContext.Result =
            new RedirectToUmbracoPageResult(
                UmbracoContext.Current.ContentCache.GetSingleByXPath("//forbidden"));
    }

It's odd that Forms authentication seems to be kicking in and redirecting you to login page for an API request. The AuthorizationFilterAttribute should return a Http 401 by default (so could deal with via web.config customErrors or httpErrors sections instead of code).

May want to review your web.config settings?