dan
dan

Reputation:

sync cookies and sessions in different subdomains (asp.net)

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.

Upvotes: 10

Views: 9199

Answers (4)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 8

D. Tony
D. Tony

Reputation: 328

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

Upvotes: 9

Ian M
Ian M

Reputation:

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

Upvotes: 1

John Hoven
John Hoven

Reputation: 4085

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

Upvotes: 0

Related Questions