20th Dec, 2007

Sharing session data across subdomains using http and https

It’s been quite a while since I last posted cos I have been quite busy lately. Anyway, I had a problem where I wanted to share session state between http and https pages (example between http://www.mysite.com and https://secure.mysite.com). Naturally, in this case, the webserver will give you a different session id because the session id is bound to the domain.

I managed to share the state by overwriting the sessionid cookie “ASP.NET_SessionId” of subdomain pages with the sessionId of the main site. However, in order for this to work you have to also change the domain property of the cookie to be that of the main site. The code is dead simple:

Response.Cookies["ASP.NET_SessionId"].Value = Session.SessionID;
Response.Cookies["ASP.NET_SessionId"].Domain = WebConfigurationManager.AppSettings["CookieDomain"].ToString();

If you do not change the domain property, the cookie will not be read properly on subdomain pages. However, for security reasons, this solution does not work across different domains since you cannot write cookies for domains that are different than the current one.

Have you ever been to Malta? All you need to know is a click away! Malta Travel Guide, Bargain Accommodation in Malta, Malta Hotels

Responses

Can you please specify where the code is supposed to be used?

Thanks for the good information, I’ve been looking for this all over the net.

Just what i needed.

by the way where did you place this code?

by default asp.net chooses ASP.NET_SessionId

but you can change it using a provider

since i created the provider above i put your code here:
public override void EndRequest(HttpContext context)
{
context.Response.Cookies[this.cookiename].Value = this._sessionid;
context.Response.Cookies[this.cookiename].Domain = this.cookiedomain;
}

Leave a response

Your response:

Categories