在重定向时保持HTTP Basic Authentification存活
我们正在使用基本身份validation的Web服务。 这一切都很好,直到Web服务的所有者实现了平衡服务。 这只是将请求重定向到不同的Web服务实例。
问题是重定向后基本身份validation失败。 有“请求身份validation凭据未通过”exception。
附加信息:
-
我们必须手动创建请求。
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();
-
我们使用HTTP 307重定向重定向
按照MSDN for HttpWebRequest.AllowAutoRedirect Property我发现了这个:
在自动重定向上清除Authorization标头 ,HttpWebRequest会自动尝试重新validation重定向的位置。 实际上,这意味着如果可能遇到重定向,应用程序无法将自定义身份validation信息放入Authorization标头中。 相反,应用程序必须实现并注册自定义身份validation模块。 System.Net.AuthenticationManager和相关类用于实现自定义身份validation模块。 AuthenticationManager.Register方法注册自定义身份validation模块。
解决方案是编写自定义身份validation模块。
在这里我发现了它:
https://msdn.microsoft.com/en-us/library/system.net.authenticationmanager.aspx
这里是AllowAutoRedirect属性页面:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect.aspx
UPDATE
您是否可以尝试使用CredentialCache而不是向webrequest添加标头?
CredentialCache myCache = new CredentialCache(); myCache.Add( new Uri("https://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); } }
我希望将来能帮助别人。
上述就是C#学习教程:在重定向时保持HTTP Basic Authentification存活分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/991395.html