views:

169

answers:

2

Hi,

I'm trying to use sub-domains in my ASP.NET website but I'm coming across a few problems with the session being reset.

I've edited my hosts file to have 'localhost', 'one.localhost' and 'two.localhost'. I can go to any of these URLs and do what I need to do and login to my system. The session mode is defined as follows in the web.config:

<sessionState cookieless="false" mode="SQLServer" timeout="300" 
        sqlConnectionString="Data Source=MyDatabase;user id=User1;password=pass"/>

I'm using SQLServer as the website will be ran as a webfarm.

What I'm finding is when I click something that causes a postback all the session is lost and a new session id is created, when this occurs my website is now 'localhost' rather than the logged in 'one.localhost' for example.

Does anyone know what might be causing this?

Cheers

+1  A: 

Basically, the domain being set in the logged in cookie is specific to one.localhost.

There are some possible hacks. see e.g. the last answer to this question:

In the login/start page, run the following:

Response.Cookies["ASP.NET_SessionId"].Value = Session.SessionID;
Response.Cookies["ASP.NET_SessionId"].Domain = ".mydomain.com";
Damien_The_Unbeliever
Here is another link that describes the solution that @Damien_The_Unbeliever posted in greater detail.http://www.know24.net/blog/ASPNET+Session+State+Cookies+And+Subdomains.aspx
thedugas
+3  A: 

You seem to have a couple of issues going on from your question:

  1. Sharing session information across multiple sub-domains.
  2. Login in to multiple domains.
  3. Staying on the correct domain during a postback.

To share the session information across multiple sub-domains, you'll need to write the session cookie to the correct domain, in this case .example.com - see more information here: "ASP.NET Session State, Cookies and Sub-domains".

If you want the user to log in on all domains simultaneously, and you're using Forms authentication, you can use the domain attribute of the forms element (note the leading period in the domain path):

<forms 
   name="name" 
   loginUrl="URL" 
   defaultUrl="URL"
   domain=".example.com">
</forms>

You'll need to configure this on all sites.

As to why you're being redirected to localhost rather than one.localhost on a postback, you'd need to take a look at the source that's been rendered (are you including some base href information, or is your form explicitly posting back to localhost instead of one.localhost)? A good tool to see what the browser is doing is Fiddler.

Finally, as a heads up for when you deploy this to multiple servers, don't forget to configure your MachineKey on all sites to ensure that they have the same value so that they can decrypt the session, login tokens, viewstate, etc correctly.

Zhaph - Ben Duguid