简体   繁体   中英

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 ?

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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM