HttpWebRequest over SSL with client credentials

I am trying to use HttpWebRequest to get an https URI that requires a username and password. If I put the URI in the browser, a dialog box asking for credentials will appear and then it will work. Using HttpWebRequest gives me 401 Unauthorized error.

The documentation for NetworkCredentials says that it does not support SSL, but I cannot find what I should use.

+5
source share
1 answer

Is the server using basic HTTP authentication or some other? If it uses HTTP basic, you can set the property Credentialsin the web request for credentials containing the correct username and password and set the property PreAuthenticateto true.

Here is an example (it has not been tested, so use it only as a guide):

var uri = new Uri("https://somesite.com/something");
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("myUserName","myPassword");
request.PreAuthenticate = true;

var response = request.GetResponse();

Note. In my experience, there is a weird behavior in the .NET Framework. You think it should do what the code says, but actually it does:

  • Send a request to the server without credentials
  • Server responds 401
  • Send a request with the credentials you gave him.
  • The server accepts the request.

I have no idea why this will be done, because it seems to be broken, so maybe it was a fad of my car, and maybe it will not happen to you.

, POSTS , , , , , HTTP- HttpWebRequest , Headers.

+5

All Articles