HttpWebRequest and forms authentication in C#

It depends on how the website is authenticating users. If they are using basic authentication or Windows authentication, then you can set the Credentials property of the HttpWebRequest class to the username/password/domain information and it should work.

However, it sounds like you have to enter the username/password on the site, which means you are going to have to login to the site first. Looking at the main page, this is what I find in the <form> element that handles login:

<form name="formlogin" method="post" action="./defalogin.php" >
  <input name="emtext" type="text" id="emtext" size="12">
  <input name="pstext" type="password" id="pstext" size="12">
  <input type="submit" name="Submit" value="Logn in" 
    onClick="return logincheck()" >
</form>

I’ve included only the relevant portions.

Given this, you have to go to the ./defalogin.php page first with the HttpWebRequest and POST the emtext and pstext values. Also, make sure you set the CookieContainer property to an instance of CookieContainer. When that call to POST returns, it’s more than likely going to be populated with a cookie which you will have to send back to the site. Just keep setting the CookieContainer property on any subsequent HttpWebRequest instances to that CookieContainer to make sure the cookies are passed around.

Then you would go to the page indicated in the link.

Of concern is also the logincheck javascript function, but looking at the script sources, it does nothing of note.

Leave a Comment