简体   繁体   English

ASP.NET MVC5 WebAPI2防止未经授权的重定向到登录页面

[英]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()? 当我返回Unauthorized()时,为什么我的WebApi2控制器将我重定向到登录页面? The same happens when I use the [Authorize] attribute. 当我使用[Authorize]属性时也会发生同样的情况。 Shouldn't the controller return a Json or XML result as requested in the Content-Type ? 控制器不应该按照Content-Type中的请求返回Json或XML结果吗? 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). 我环顾网络似乎表单身份验证模块正在抓取我的401响应并将其转换为302.这很奇怪,因为我的身份验证模式是“无”(不是表单)。 Moreover I have read that this 'feature' has been fixed in .Net 4.5 (which I am running). 此外,我已经读过这个'功能'已在.Net 4.5(我正在运行)中修复。

I have tried overriding my Application_EndRequest in my Global.asax.cs 我已经尝试在我的Global.asax.cs中覆盖我的Application_EndRequest

        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). 它没有很好地工作(返回IIS Html页面)。 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. 将Cookie身份验证中间件与Web API和401响应代码一起使用您可以通过覆盖CookieAuthenticationProvider中的OnApplyRedirect事件来自定义它。 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"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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