• 0

Making authenticated WebRequest in C#


Question

Hi there,

I'm trying to make a WebRequest in C# to a website that requires credentials.

Using the username and password in IE works, but doing it through code doesn't.

Maybe I have some misplaced code?

public bool WebRequestMethod(string uri) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = new NetworkCredential(securelyStoredUserName, securelyStoredPassword);
request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;

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

return false;
}

Thanks,

David.

Link to comment
https://www.neowin.net/forum/topic/813426-making-authenticated-webrequest-in-c/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

I think you might find your answer in the Community Content section of the following MSDN Entry: http://msdn.microsoft.com/en-us/library/sy...ationlevel.aspx

  Quote
- When you set the WebRequest.AuthenticationLevel = AuthenticationLevel.MutualAuthRequired property, you will end up seeing the exception on the client which says:

System.Net.WebException: The request was canceled

---> System.Net.ProtocolViolationException: The requirement for mutual authentication was not met by the remote server.

- However, if you take a System.Net/ Network trace of the request what you will end up seeing is that the client sends the entire request (eg: POST with the entity body), the server processes the entire request and sends a response back to the client and only then, the client gets the exception.

- This behavior is by design and is the correct behavior. The reason being: the client cannot guarantee that the mutual authentication has been successful until it receives a "full" response from the server. The client can make a second call to InitializeSecurityContext only after it receives a WWW-Authenticate header with the server's Kerberos token. Only after this happens, it can call QueryContextAttributes to actually see if mutual authentication was successful.

- Since the server can respond back with a "full response" only after the entire request is complete, the only way the client can guarantee this is after getting a status code of (4xx or 2xx) from the server; which happens after sending the entity body.

- If you want to guarantee that the client & server mutually authenticate with each other, then you can send a dummy/ fake HEAD/ GET request to the server. If there is no mutual Authentication (the client and server talking anything but Kerberos), the HEAD/ GET request will fail with the expected Exception.

- You can then decide whether or not to send further POST requests.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.