Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC5 WebAPI2 Prevent Unauthorized Redirect to Login Page

Why is my WebApi2 controller redirecting me to the Login page when I return Unauthorized()? The same happens when I use the [Authorize] attribute. Shouldn't the controller return a Json or XML result as requested in the Content-Type ? Redirecting me to the Login page is a waste of resources and completely useless to an application client.

Ive looked around the web It seems that the forms authentication module is grabbing my 401 response and converting it into a 302. This is odd because my Authentication Mode is 'none' (not forms). Moreover I have read that this 'feature' has been fixed in .Net 4.5 (which I am running).

I have tried overriding my Application_EndRequest in my Global.asax.cs

        protected void Application_EndRequest()
    {
        var context = new HttpContextWrapper(Context);
        // If we're an ajax request, and doing a 302, then we actually need to do a 401
        if (Context.Response.StatusCode == 302 && context.Request.ContentType.StartsWith("application"))
        {
            Context.Response.Clear();
            Context.Response.ClearContent();
            Context.Response.StatusCode = 401;
            context.Response.RedirectLocation = null;
            Context.Response.End();
        }
    }

It did not work very well (returned an IIS Html page). What is the next step ?

like image 245
nVentimiglia Avatar asked Nov 07 '13 19:11

nVentimiglia


1 Answers

Using cookie authentication middleware with Web API and 401 response codes You can customize it, by overriding OnApplyRedirect event in your CookieAuthenticationProvider. Read blog for further explanation.

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
   AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
   LoginPath = new PathString("/Account/Login"),
   Provider = new CookieAuthenticationProvider
   {
      OnApplyRedirect = ctx =>
      {
         if (!IsAjaxRequest(ctx.Request))
         {
            ctx.Response.Redirect(ctx.RedirectUri);
         }
     }
   }
});

And in same class:

private static bool IsAjaxRequest(IOwinRequest request)
{
   IReadableStringCollection query = request.Query;
   if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest"))
   {
      return true;
   }
   IHeaderDictionary headers = request.Headers;
   return ((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest"));
}
like image 170
Bcelik Avatar answered Sep 28 '22 04:09

Bcelik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!