Pav*_*kiy 6 c# web-services http basic-authentication http-headers
我们正在使用基本身份验证的Web服务.这一切都很好,直到Web服务的所有者实现了平衡服务.这只是将请求重定向到不同的Web服务实例.
问题是重定向后基本身份验证失败.有"请求身份验证凭据未通过"异常.
附加信息:
我们必须手动创建请求.
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();
Run Code Online (Sandbox Code Playgroud)我们通过HTTP 307重定向重定向
按照 MSDN 的 HttpWebRequest.AllowAutoRedirect 属性我发现了这个:
自动重定向时会清除 Authorization 标头,并且 HttpWebRequest 自动尝试对重定向位置重新进行身份验证。实际上,这意味着如果可能遇到重定向,应用程序无法将自定义身份验证信息放入 Authorization 标头中。相反,应用程序必须实现并注册自定义身份验证模块。System.Net.AuthenticationManager 和相关类用于实现自定义身份验证模块。AuthenticationManager.Register 方法注册自定义身份验证模块。
解决方案是编写自定义身份验证模块。
这是我发现的:
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 添加标头吗?
CredentialCache myCache = new CredentialCache();
myCache.Add(
new Uri("http://www.contoso.com/"),"Basic",new NetworkCredential(UserName,SecurelyStoredPassword));
req.Credentials = myCache;
Run Code Online (Sandbox Code Playgroud)