.net 在 WebRequest 中强制进行基本身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2764577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Forcing Basic Authentication in WebRequest
提问by Himanshu
I am integrating web service that will use an HTTP-POST to request and retrieve data. The remote server requires basic authentication as per RFC 2617
我正在集成将使用 HTTP-POST 请求和检索数据的 Web 服务。远程服务器需要根据 RFC 2617 进行基本身份验证
My attempts to authenticate are failing.
我的身份验证尝试失败。
It fails in that, even though I attach a 'NetworkCredential' object to the 'Credentials' property of a 'HttpWebRequest' object, no authentication information is sent in the header, even if I set 'PreAuthenticate' = true.
它失败了,即使我将“NetworkCredential”对象附加到“HttpWebRequest”对象的“Credentials”属性,标题中也不会发送任何身份验证信息,即使我设置了“PreAuthenticate”=true。
What am I missing?
我错过了什么?
//chunk used
//使用的块
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;
回答by Samuel Hyman
I've just found this very handy little chunk of codeto do exactly what you need. It adds the authorization header to the code manually without waiting for the server's challenge.
我刚刚发现这个非常方便的小代码块可以完全满足您的需求。它手动将授权标头添加到代码中,而无需等待服务器的质询。
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;
}
Use it like this
像这样使用它
var request = WebRequest.Create("http://myserver.com/service");
SetBasicAuthHeader(request, userName, password);
var response = request.GetResponse();
回答by Prateek
Improving a little bit on samuel-Hyman's accepted answer. Instead of using the default encoding "ISO-8859-1" should be used as mentioned in this answer What encoding should I use for HTTP Basic Authentication?
对 samuel-Hyman 接受的答案稍作改进。不应使用默认编码“ISO-8859-1”,如本答案中所述,我应该使用什么编码进行 HTTP 基本身份验证?
So the code would look like this:
所以代码看起来像这样:
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;
}
回答by JuanPablo
Here's my solution for OAuth. The value is in variable json.
这是我的 OAuth 解决方案。该值在变量 json 中。
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();
回答by Chris
I found this question while looking for the answer, the answer given works but is not flexible so if you would like a better .NET way of doing this.
我在寻找答案时发现了这个问题,给出的答案有效但不灵活,所以如果您想要更好的 .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;
You can replace "Basic" with "Digest", "NTLM" or "Negotiate" as well as this giving the ability to add multiple types to the cache as well.
您可以将“Basic”替换为“Digest”、“NTLM”或“Negotiate”,这样也可以将多种类型添加到缓存中。

