在WebRequest中强制执行基本身份validation
我正在集成将使用HTTP-POST请求和检索数据的Web服务。 远程服务器需要根据RFC 2617进行基本身份validation
我尝试authentication失败。
即使我将“NetworkCredential”对象附加到“HttpWebRequest”对象的“Credentials”属性上,即使设置了“PreAuthenticate”= true,也不会在标头中发送authentication信息。
我错过了什么?
//使用大块
NetworkCredential netCredential = new NetworkCredential(" uid", "pwd"); Uri uri = new Uri("http://address of services"); ICredentials credentials = netCredential.GetCredential(uri, "Basic"); objRegistration.Credentials = credentials; objRegistration.PreAuthenticate = true;
我刚刚发现这个非常方便的一小块代码来完成你所需要的。 它手动添加授权标头到代码而不用等待服务器的挑战。
public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword) { string authInfo = userName + ":" + userPassword; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); request.Headers["Authorization"] = "Basic " + authInfo; }
像这样使用它
var request = WebRequest.Create("http://myserver.com/service"); SetBasicAuthHeader(request, userName, password); var response = request.GetResponse();
萨米埃尔 – 杰克接受的答案略有改善。 应该使用默认编码“ISO-8859-1”,而不是像本答复中提到的那样使用什么编码来进行HTTP基本authentication?
所以代码看起来像这样:
public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword) { string authInfo = userName + ":" + userPassword; authInfo = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(authInfo)); request.Headers["Authorization"] = "Basic " + authInfo; }
这是我的OAuth解决scheme。 值是在variablesjson中。
var myUri = new Uri(fullpath); var myWebRequest = WebRequest.Create(myUri); var myHttpWebRequest = (HttpWebRequest)myWebRequest; myHttpWebRequest.PreAuthenticate = true; myHttpWebRequest.Headers.Add("Authorization", "Bearer " + AccessToken); myHttpWebRequest.Accept = "application/json"; var myWebResponse = myWebRequest.GetResponse(); var responseStream = myWebResponse.GetResponseStream(); if (responseStream == null) return null; var myStreamReader = new StreamReader(responseStream, Encoding.Default); var json = myStreamReader.ReadToEnd(); responseStream.Close(); myWebResponse.Close();
我发现这个问题,同时寻找答案,给出的答案,但不灵活,所以如果你想要一个更好的.NET方式做到这一点。
Uri uri = new Uri("http://address of services"); HttpWebRequest objRegistration = (HttpWebRequest)WebRequest.Create(url); CredentialCache credentials = new CredentialCache(); NetworkCredential netCredential = new NetworkCredential(" uid", "pwd"); credentials.Add(uri, "Basic", netCredential); objRegistration.Credentials = credentials;
您可以将“基本”replace为“摘要”,“NTLM”或“协商”,也可以将多种types添加到caching中。