C# Invalid Server Certificate Handling

chttpwebrequest

I'm behind a firewall that asks me to enter credentials before letting me access internet. So my first http request is intercepted and then redirected to a secure server that prompts me to enter my credentials. So I get response with following headers, when I send a get request to google.com
172.24.64.1 is the server in question.

Connection close

Content-Length 225

Cache-Control no-cache

Content-Type text/html

Location https://172.24.64.1:1005/x?70cea2e7d3de9b77

I then get hold of the Location header of the response that redirected me, and then try to establish a connection with the server with invalid certificate.

HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(location);

However, loginRequest.GetResponse() fails with the exception message: "the underlying connection was closed. Could not establish trust relationship for the SSL/TLS secure channel"

I then put this line in my code before the line asking for HttpWebResponse:
Using a self-signed certificate with .NET's HttpWebRequest/Response

ServicePointManager.ServerCertificateValidationCallback = delegate{return true;};

However, I get the following exception:

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

However, I don't see any authentication request in the aforementioned headers. So I don't understand what the problem is. Can somebody please suggest what I should do in this situation.

Best Answer

The 401 indicates that the connection succeeded, but it's now challenging you for authentication credentials, probably via NTLM/Negotiate. You'll need to attach a credential for your web request to automatically authenticate. (see HttpWebRequest not passing Credentials for instance)

You can use Fiddler (www.fiddler2.com) to watch this traffic and understand what's happening.