Search code examples
c#sslhttpwebrequestbasic-authentication

Web request (GET) with Basic Auth and SSL failing


I have browsed through all questions in stackoverflow but I still cannot make my request working. The server (I have no access to it, so I do not know what is going on over there) is always responding with 403.

I was told that I have to use Basic Auth with HTTPS. At first I tried it with PostMan (Chrome add-on) and it worked perfectly. Fiddler says that PostMan has sent this request:

GET https://mypage.com/api/topic HTTP/1.1
Host: mypage.com
Connection: keep-alive
Authorization: Basic asdfasdfasdfasdfasdfasdf
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
Postman-Token: 7363b868-cc6e-1dff-d5d0-c7a0c1924fa7
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=imxY132456123Scai90Nrsv

I wanted to reproduce this in our C# application, but whatever I try I get a 403 answer from the server. This is (one) of the versions in C# I have tried:

NetworkCredential nc = new NetworkCredential(Login, Password);
CredentialCache cc = new CredentialCache();
cc.Add("mypage.com", 443, "Basic", nc);

WebRequest request = WebRequest.Create("https://mypage.com/api/topic");
request.Credentials = cc;
request.PreAuthenticate = true;
request.Method = "GET";
WebResponse response = request.GetResponse();

That is what is sent according to Fiddler:

GET https://mypage.com/api/topic HTTP/1.1
Host: mypage.com
Connection: Keep-Alive

Obviously there are some things missing. I am wondering which ones (like user-agent?) are really essential and I hope you can help me fix the problem.


Solution

  • I could swear that I have already tried setting headers exactly this way. Probably I have been stuck for too long and made a mistake...

    So here is my solution:

    string auth = Convert.ToBase64String(Encoding.Default.GetBytes(Login + ":" + Password));
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mypage.com/api/topic");
    request.Headers.Add("Authorization", "Basic " + auth);
    

    Thank god, it works now.