I'm writing an application that will need to open up browser windows (probably can stick to IE) to websites that use Forms Authentication. The trick is that they need to be authenticated already, in order to save time due to the sheer number of sites we need to get into. (Eventually I'll be screen scraping them and processing the data... but I'll still need to get the authentication piece working so they can click through to the real site when needed.)
I've got the Forms Authentication piece working, in that I can use an HttpWebRequest to get the html and just pass it through to the browser. However I can't get it to transfer the cookies to the client browser so that it can go to the actual website.
I'm getting the System.Net.Cookies for the authentication, and I've tried copying them into System.Web.HttpCookies and adding those to the Response object. If I put a link on the page or use Response.Redirect to go to the website it doesn't work, it acts as if the user is not authenticated.
Anyone have any idea how I would pull this off?
Here's the current code, in case that makes this more clear:
Dictionary<string, string> formValues = new Dictionary<string, string>(4);
formValues.Add("txbUserName", "USERNAME");
formValues.Add("txbPassword", "PASSWORD");
formValues.Add("SubmitB", "Log In");
HttpWebRequest webRequest;
StreamReader responseReader;
string responseData;
//This authenticates an HttpWebRequest and returns it
webRequest = FormsAuthHttpWebRequest.Create("REQUESTURI", "LOGINURI",
formValues) as HttpWebRequest;
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
responseReader.Close();
foreach (Cookie cookie in webRequest.CookieContainer.GetCookies(new Uri("SITEURI")))
{
HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Value)
{
Domain = cookie.Domain,
Expires = cookie.Expires,
Path = cookie.Path,
HttpOnly = cookie.HttpOnly,
Secure = cookie.Secure
};
Response.Cookies.Add(httpCookie);
}
Response.Redirect("REQUESTURI");