在强制WebRequest的基本身份验证身份验证、基本、WebRequest

2023-09-02 21:27:55 作者:▲ 素颜谁敢与君亡

这将使用

我是集成Web服务 HTTP-POST请求和检索数据。远程服务器 需要基本身份验证按照RFC 2617

我的验证尝试失败了。

据失败的,尽管我附上'的NetworkCredential对象为HttpWebRequest的'对象'证书'的财产,不进行身份验证信息在标头中发送, 即使我设置'preAuthenticate'=真。

我在想什么?

//使用的组块

 的NetworkCredential netCredential =新的NetworkCredential(UID,PWD);

开放的我们的uri =新的URI(HTTP://地址服务);

ICredentials凭证= netCredential.GetCredential(URI,基本法);

objRegistration.Credentials =凭证;

objRegistration preAuthenticate = TRUE。
 

解决方案

我刚刚发现这非常方便的小chunk code 做正是你需要的。它添加了授权头到code手动无需等待服务器的挑战。

 公共无效SetBasicAuthHeader(WebRequest的要求,字符串username,字符串的userPassword)
{
    字符串AUTHINFO =用户名+:+的userPassword;
    AUTHINFO = Convert.ToBase64String(Encoding.Default.GetBytes(AUTHINFO));
    request.Headers [授权] =基本+ AUTHINFO;
}
 

使用像这样

  VAR请求= WebRequest.Create(http://myserver.com/service);
SetBasicAuthHeader(请求,用户名,密码);

变种响应= request.GetResponse();
 

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.

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.

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;

解决方案

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;
}

Use it like this

var request = WebRequest.Create("http://myserver.com/service");
SetBasicAuthHeader(request, userName, password);

var response = request.GetResponse();