30 March 2010

How to add a forms authentication cookie to the request

A common problem is how to add an forms authentication cookie to the request.
The solution is to add the forms authentication cookie when performing a HttpWebRequest.


Uri uri = new Uri("http://services.mysite.com/document/documentservice.svc");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);       
 
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Cookie authenticationCookie = new Cookie(FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority);
webRequest.CookieContainer = new CookieContainer();
webRequest.CookieContainer.Add(authenticationCookie);
WebResponse myResponse = webRequest.GetResponse();
Stream stream = myResponse.GetResponseStream();

2 comments:

Anonymous said...

Instead of using "HttpContext.Current.Request.Url.Authority" I had to use "FormsAuthentication.Domain". This might have something to do with the multi-level domain for example, passing a cookie form site1.company.com to site2.company.com.

Anonymous said...

It works!!!! Thank you...