views:

287

answers:

1

Hi all,

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/>");
        }

    }
A: 

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);
Pent Ploompuu
I fixed it but still got the error.The remote server returned an error: (401) Unauthorized.I'm sure the password is correct (Firefox works), maybe it's a certificate issue?
newth
Maybe you need to add the domain also to the `NetworkCredential` class (If you enter the username as "domain\username" in firefox).
Pent Ploompuu
I don't use domain in Firefox also, just username and password.
newth
You could try giving the credentials directly to the request: `request.Credentials = netCredential; request.PreAuthenticate = false;`.
Pent Ploompuu
Still not working, FYI.
newth