Previous     Next

Copying cookies across domains in ASP.Net

If you logging in to remote sites using HttpWebRequest then you are probably used to supplying a CookieContainer object to keep track of login sessions etc. However, sometimes a login will do a redirect, leaving your cookies referring to the login url and not usable on the next url.

Eg:
Post login details to
http://yourdomain/login
Site redirects (302) to:
http://yourdomain/admin

The login cookie is stuck on http://yourdomain/login and is not used at http://yourdomain/admin, so the login fails.

The key is to set:
WebRequestObject.AllowAutoRedirect = false
in the HttpWebRequest for http://yourdomain/login

Code to copy cookies:


Dim oOldCookies As New CookieContainer
Dim oNewCookies As New CookieContainer
Dim oOldCookiesCol As New CookieCollection

'Do HttpRequest on http://yourdomain/login, place cookies in oOldCookies
'Remember to set WebRequestObject.AllowAutoRedirect = false

oOldCookiesCollection = oOldCookies.GetCookies(New System.Uri("http://www.olddomain.com"))
For iC = 0 To oOldCookiesCol.Count - 1
     oNewCookies.Add(New Cookie(oOldCookiesCol(iC).Name, oOldCookiesCol(iC).Value, "", "http://www.newdomain.com"))
Next

'Now do HttpRequest on http://yourdomain/admin, using oNewCookies

This post brought to you by WeGotDomain.com - Over 10,000 Aged domains for sale!

Related posts:

  1. Easy Cross Domain Cookies (Sharing cookies between domains)
  2. How to set third-party cookies with iframe Facebook Applications
  3. Opening a new browser window with POST data
  4. SEOMoz Linkscape API wrapper in VB.Net

If you liked this, then subscribe to my RSS feed