401 Unauthorized returned on GET request (https) with correct credentials

Posted by Johnny Grass on Stack Overflow See other posts from Stack Overflow or by Johnny Grass
Published on 2011-03-05T23:58:58Z Indexed on 2011/03/06 0:11 UTC
Read the original article Hit count: 268

Filed under:
|
|
|
|

I am trying to login to my web app using HttpWebRequest but I keep getting the following error:

System.Net.WebException: The remote server returned an error: (401) Unauthorized.

Fiddler has the following output:

Result Protocol  Host           URL
200    HTTP      CONNECT        mysite.com:443
302    HTTPS     mysite.com     /auth
401    HTTP      mysite.com     /auth

This is what I'm doing:

// to ignore SSL certificate errors
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
     return true;
}

try
{   
    // request
    Uri uri = new Uri("https://mysite.com/auth");
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri) as HttpWebRequest;
    request.Accept = "application/xml";

    // authentication
    string user = "user";
    string pwd = "secret";   
    string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
    request.Headers.Add("Authorization", auth);
    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

    // response.
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Display 
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();
    Console.WriteLine(responseFromServer);

    // Cleanup 
    reader.Close();
    dataStream.Close();
    response.Close();
}
catch (WebException webEx)
{
   Console.Write(webEx.ToString());
}

I am able to log in to the same site with no problem using ASIHTTPRequest in a Mac app like this:

NSURL *login_url = [NSURL URLWithString:@"https://mysite.com/auth"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:login_url];
[request setDelegate:self];
[request setUsername:name];
[request setPassword:pwd];  
[request setRequestMethod:@"GET"];
[request addRequestHeader:@"Accept" value:@"application/xml"]; 
[request startAsynchronous];    

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET