c# - 在重定向时保持 HTTP 基本身份验证有效

标签 c# web-services http http-headers basic-authentication

我们正在使用具有基本身份验证的网络服务。 一切正常,直到 Web 服务的所有者实现平衡服务。 这只是将请求重定向到不同的 Web 服务实例。

问题是在被重定向后基本认证失败。 存在“请求身份验证凭据未通过”异常。

附加信息:

  1. 我们必须手动创建请求。

        var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(Settings.Default.HpsmServiceAddress));
    
        req.Headers.Add("Authorization", "Basic aaaaaaaaaaa");
        req.PreAuthenticate = true;
        req.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;
        req.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)";
        req.KeepAlive = false;
    
        ServicePointManager.Expect100Continue = false;
    
        req.ContentType = "text/xml; charset=utf-8";
        req.Method = "POST";
        req.Accept = "gzip,deflate";
        req.Headers.Add("SOAPAction", actionName);
        byte[] buffer = Encoding.UTF8.GetBytes(envelop);
        Stream stm = req.GetRequestStream();
        stm.Write(buffer, 0, buffer.Length);
        stm.Close();
    
        WebResponse response = req.GetResponse();
        string strResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
        response.Dispose();
    
  2. 我们使用 HTTP 307 重定向进行重定向

最佳答案

按照 HttpWebRequest.AllowAutoRedirect 属性的 MSDN,我发现了这个:

The Authorization header is cleared on auto-redirects and HttpWebRequest automatically tries to re-authenticate to the redirected location. In practice, this means that an application can't put custom authentication information into the Authorization header if it is possible to encounter redirection. Instead, the application must implement and register a custom authentication module. The System.Net.AuthenticationManager and related class are used to implement a custom authentication module. The AuthenticationManager.Register method registers a custom authentication module.

解决方案是编写自定义身份验证模块。

这是我发现的:

http://msdn.microsoft.com/en-us/library/system.net.authenticationmanager.aspx

这里是 AllowAutoRedirect 属性页面:

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect.aspx

更新

您可以尝试使用 CredentialCache 而不是向 webrequest 添加 header 吗?

CredentialCache myCache = new CredentialCache();

myCache.Add(
new Uri("http://www.contoso.com/"),"Basic",new NetworkCredential(UserName,SecurelyStoredPassword));
req.Credentials = myCache;

关于c# - 在重定向时保持 HTTP 基本身份验证有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14056766/

相关文章:

java - 在 Java 中使用 Contract-First 的 Web 服务周期

web-services - Document 风格和 RPC 风格的通信有什么区别?

c# - 如何比较linq中2个列表中子项的属性

C# 错误还是脑筋急转弯? Cast 仅与 Coalesce (??) 运算符一起使用

java - weblogic-maven-plugin 中缺少目标

http - 为什么 HTTP 不是消息传递协议(protocol)? (根据 RabbitMQ)

windows - 使用以太网电缆连接两台计算机

http - 数组究竟是如何进行 urlencode 编码的?

c# - MessageBox 是桌面模态的

c# - 在 C# 中舍入 double 值