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:
- Set a request's
CookieContainertoglobalCookieContainer. - POST username and password to a logon URL. (after that step the container still reports the Cookie count is 0).
- Create another
HttpWebRequestinstance and set theglobalCookieContainerto request'sCoockieContainer. - 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?
HttpWebRequest.Credentialsis meant to be used when the authentication is performed through one of the schemes in theAuthenticationSchemesenum. 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
NetworkCredentialon the client side and implementingIAuthenticationModuleon the server side.