views:

2473

answers:

4

I am building a site in asp.net and have multiple subdomains. For example, one.cookies.com two.cookies.com

I want my users to be able to login at either subdomain and be logged in for both websites. In addition, I'd like the sessions and cookies to be in sync. So far I haven't found a reliable way to do this.

A: 

I beleive make the cookie for http://cookies.com. (No subdomain or www listed)

benjynito
+3  A: 

When you create the cookie you can set the domain:

HttpCookie cookie = new HttpCookie("name", "value");
cookie.Domain = "cookies.com";

This will allow your cookie to be accessible from all subdomains of cookies.com.

If you are using FormsAuthentication then you can set the domain for the auth cookie in web.config:

<forms name=".ASPXAUTH" 
       loginUrl="login.aspx" 
       defaultUrl="default.aspx" 
       protection="All" 
       timeout="30" 
       path="/" 
       requireSSL="false" 
       domain="cookies.com">
</forms>

Remember that for the single sign on to work on multiple subdomains your ASP.NET applications must share the same machine keys as explained in this CodeProject article.

Sharing sessions between different subdomains (different worker processes) is more difficult because sessions are constrained to an application and you will have to implement a custom session synchronization mechanism.

Darin Dimitrov
+1  A: 

Yes, you need to use ".cookies.com" not "cookies.com"

Are you sure? Check this out [http://msdn.microsoft.com/en-us/library/ms178194.aspx], it shows Response.Cookies["domain"].Domain = "contoso.com"; then says "The cookie will then be available to the primary domain as well as to sales.contoso.com and support.contoso.com domains."
Shane N
+1  A: 

If you want to sync the ASP.NET session and you aren't using forms authentication (for example, your site has no login), try adding the following code to your Globals.asax file. This worked like a champ for me and saved me some serious grief.

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
  /// only apply session cookie persistence to requests requiring session information
  #region session cookie

  if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState )
  {
    /// Ensure ASP.NET Session Cookies are accessible throughout the subdomains.
    if (Request.Cookies["ASP.NET_SessionId"] != null && Session != null && Session.SessionID != null)
    {
      Response.Cookies["ASP.NET_SessionId"].Value = Session.SessionID;
      Response.Cookies["ASP.NET_SessionId"].Domain = ".know24.net"; // the full stop prefix denotes all sub domains
      Response.Cookies["ASP.NET_SessionId"].Path = "/"; //default session cookie path root         
    }
  }
  #endregion    
}

I found this originally posted here: http://www.know24.net/blog/ASPNET+Session+State+Cookies+And+Subdomains.aspx

D. Tony