When HttpWebRequest.Credentials should be used

355 views Asked by At

I tried to perform a POST using a HttpWebRequest instance to a web url that requires an authentication (an ASP.NET MV3 standart [Authorize] decorated action method with build-in membership system), but providing login and passowrd as NetworkCredentials in HttpWebRequest didn't do the trick.

I ended up using a global CookieContainer and two HttpWebRequests:

  1. Set a request's CookieContainer to globalCookieContainer.
  2. POST username and password to a logon URL. (after that step the container still reports the Cookie count is 0).
  3. Create another HttpWebRequest instance and set the globalCookieContainer to request's CoockieContainer.
  4. POST to a final url that requires authentication. For some reason, this time second request object provides the cookies as a part of a request and it goes through.

An entire "magic" of cookie management isn't discribed anywhere well (I really tried to search around).

We've got this scenario covered. But in what cases HttpWebRequest.Credentials should be used?

1

There are 1 answers

1
Jon On BEST ANSWER

HttpWebRequest.Credentials is meant to be used when the authentication is performed through one of the schemes in the AuthenticationSchemes enum. Among others, this includes Basic and Digest HTTP auth, NTLM and Kerberos.

That said, you can cook up your own custom authentication schemes by deriving from NetworkCredential on the client side and implementing IAuthenticationModule on the server side.