在 WebRequest 中强制进行基本身份验证 [英] Forcing Basic Authentication in WebRequest
问题描述
我正在集成将使用HTTP-POST 请求和检索数据.远程服务器需要根据 RFC 2617 进行基本身份验证
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
我的身份验证尝试失败.
My attempts to authenticate are failing.
它失败了,即使我将NetworkCredential"对象附加到HttpWebRequest"对象的Credentials"属性,也没有在标头中发送身份验证信息,即使我设置了 'PreAuthenticate' = true.
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 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;
推荐答案
我刚刚发现这个非常方便的小代码块 来做你所需要的.它手动将授权头添加到代码中,无需等待服务器的质询.
I've just found this very handy little chunk of code to 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;
}
像这样使用
var request = WebRequest.Create("http://myserver.com/service");
SetBasicAuthHeader(request, userName, password);
var response = request.GetResponse();
这篇关于在 WebRequest 中强制进行基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!