在重定向时保持HTTP Basic Authentification存活

我们正在使用基本身份validation的Web服务。 这一切都很好,直到Web服务的所有者实现了平衡服务。 这只是将请求重定向到不同的Web服务实例。

问题是重定向后基本身份validation失败。 有“请求身份validation凭据未通过”exception。

附加信息:

  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重定向重定向

按照MSDN for HttpWebRequest.AllowAutoRedirect Property我发现了这个:

在自动重定向上清除Authorization标头 ,HttpWebRequest会自动尝试重新validation重定向的位置。 实际上,这意味着如果可能遇到重定向,应用程序无法将自定义身份validation信息放入Authorization标头中。 相反,应用程序必须实现并注册自定义身份validation模块。 System.Net.AuthenticationManager和相关类用于实现自定义身份validation模块。 AuthenticationManager.Register方法注册自定义身份validation模块。

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

在这里我发现了它:

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

这里是AllowAutoRedirect属性页面:

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

UPDATE

您是否可以尝试使用CredentialCache而不是向webrequest添加标头?

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

确实, CredentialCache正常工作。 但是,如果您想添加多个基本身份validation凭据(例如,如果您知道重定向),您可以使用我所做的以下function:

 private void SetNetworkCredential(Uri uriPrefix, string authType, NetworkCredential credential) { if (request.Credentials == null) { request.Credentials = new CredentialCache(); } if (request.Credentials.GetCredential(uriPrefix, authType) == null) { (request.Credentials as CredentialCache).Add(uriPrefix, authType, credential); } } 

我希望将来能帮助别人。