I'm trying to connect to a web service using C# and digest authentication, but every time I got the 401 - Not Authorized
error. But when I try to reach the service over Firefox, everything's OK. When I use IE8, my password is not accepted and I got a 401.
Do you have any ideas? Thanks for the help.
Here's the test code I'm using:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback
= delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
Uri uri = new Uri(URL);
NetworkCredential netCredential = new NetworkCredential(username, password);
CredentialCache cache = new CredentialCache();
cache.Add(URL, 443, "Digest", netCredential);
WebRequest request = WebRequest.Create(URL);
request.Credentials = cache;
request.PreAuthenticate = true;
request.Method = "POST";
WebResponse response;
try
{
response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
Response.Write(result);
response.Close();
reader.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message + "<br/><br/><br/>");
Response.Write("Request Headers<br/><br/>");
WebHeaderCollection headers = request.Headers;
// Get each header and display each value.
foreach (string key in headers.AllKeys)
{
string value = headers[key];
Response.Write(key + ": " + value);
Response.Write("<开发者_运维技巧;br/><br/>");
}
}
You are using the wrong overload of CredentialCache.Add
, you should use CredentialCache.Add(Uri, string, NetworkCredential)
instead. The first one (with the port number) is only for SMTP.
cache.Add(uri, "Digest", netCredential);
精彩评论