9

The default usage of HttpClient and HttpWebRequest .NET classes is setting Credentials property and then asking the class instance to perform an HTTP request. If the target requres Basic authorization the following happens (those classes do this under the hood and Fiddler shows what's going on):

  • the first request is sent without Authorization header
  • the server declines and responds with HTTP 401
  • the client resends the very same request this time with Authorization header containing the properly encoded data from Credentials property

and this is the default behavior. So unless the user validates his application and takes extra steps every request is sent twice - the first one is universally rejected.

My question is - what's the reason for such default behavior? The client class has its Credentials property set so it kind of assumes the user wants to use those credentials for authentication. Why not just send the appropriate header with the first request? Would doing the latter somehow compromise the client?

21

This behaviour is specified by RFC2617. The reason for the extra round trip is that the server can request different kinds of authentication: basic, digest, etc. If you know in advance that the server takes basic authentication, then as you say, you can save a round trip. But that isn't the default, and I think the .NET libraries are right to expose this as they do.

  • 2
    Also note that http comes from a purely browser interactive age, where the browser would first need the information from the server that authentication is needed before showing the username/password dialogue. – PlasmaHH Sep 10 '14 at 15:09
  • 1
    The Challenge-Response pattern also allows for authentication schemes that could potentially protect against replay attack. If the Challenge 401 contains (non-repeating) data (nonce) that the client needs to combine with his credentials, then the Response would only be valid to that particular Challenge. This is how digest auth works. – Aron Sep 11 '14 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.