【问题标题】:How to prevent 302 redirect using windows authentication如何使用 Windows 身份验证防止 302 重定向
【发布时间】:2016-10-09 00:58:23
【问题描述】:

我正在构建一个 MVC5 Web 应用程序,其中 Web API2 用于后端服务器调用,Angularjs 用于客户端代码。该应用程序正在使用 Windows 身份验证。对于 Web API 控制器中的某些方法,我已在特定用户角色上设置了 Authorize 属性。问题是当身份验证失败时,它会弹出 Windows 安全对话框供用户登录。有没有办法阻止此对话框出现并重定向到特定 URL 或返回失败状态代码和错误消息?

我在网上搜索,找到了OWIN认证的解决方案,但没有找到windows认证的解决方案。

【问题讨论】:

    标签: angularjs asp.net-web-api2 asp.net-mvc-5 asp.net-authentication


    【解决方案1】:

    在 Asp.Net Web API 中创建一个消息处理程序,您可以在其中删除 WWW-Authenticate 标头,这样浏览器就不会弹出窗口。您可以在此级别进行许多自定义。

    要创建您自己的消息处理程序,您需要扩展DelegatingHandler,如下所示

     public class MyHandler : DelegatingHandler
     {
           protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
           {
    
                   //Your code goes here
                   var response = await base.SendAsync(request,cancellationToken);
                   if(response.StatusCode == HttpStatusCode.Unauthorized)
                   {
                      // remove WWW-Authenticate from the header and add Location header to redirect to a page
                       OR
                     // Create a new response and then return that response
                   }
                   return response;
    
           }
    
     }
    

    【讨论】:

    • 如果创建新响应,我可以让它工作,但如果我想保持 401 状态怎么办?我看看 response.Headers.WwwAuthenticate 是空的,response.Location 是空的。
    猜你喜欢
    • 2016-07-11
    • 1970-01-01
    • 2021-10-23
    • 2020-09-16
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多