如何使用HttpWebRequest.Credentials物业基本身份验证?如何使用、身份验证、物业、基本

2023-09-04 00:27:14 作者:谎言最暖人心i

我如何使用WebRequest 证书属性发送基本认证头? 为什么没有授权头与发送,即使 preAuthenticate 设置为true的要求?

 的WebRequest请求=(HttpWebRequest的)WebRequest.Create(https://api.github.com/user);
request.Credentials =新的NetworkCredential(githubUsername,githubPassword);
请求preAuthenticate = TRUE。
变种响应= request.GetResponse();
 

解决方案

服务器应该发送一个HTTP 401未授权响应code的包含的一个WWW身份验证的HTTP标头。

  WWW身份验证:基本境界=榜样
 

在preAuthenticate属性只适用的在的验证已经发生。从MSDN:

  

真正用后请求发送一个HTTP Authorization头   验证已经发生;否则为false。缺省值是   假的。

进行更深入的解释请参见其他的答案。

How can I use the Webrequest Credentials Property to send an basic authentication header? Why isn't the Authorization header send with the request even whenPreAuthenticate is set to true?

WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");
request.Credentials = new NetworkCredential("githubUsername", "githubPassword");
request.PreAuthenticate = true;
var response = request.GetResponse();

解决方案

The server should send a HTTP 401 Not Authorized response code containing a WWW-Authenticate HTTP header.

WWW-Authenticate: Basic realm="example"

The PreAuthenticate property only works after authentication has taken place. From MSDN:

true to send an HTTP Authorization header with requests after authentication has taken place; otherwise, false. The default is false.

See other answers for more in depth explanation.