How can you keep a session across multiple subdoma

2019-01-23 21:40发布

问题:

A shopping cart application I'm working on jumps domain when it goes from the normal page into the submit-your-details page.

Long story short there are two copies of the application deployed: one server for the 'main' site and one server with an ev certificate running on https for the customer details (including payment; this is a PCI compliance issue).

My question is this:

When jumping from http://shop.domain -> https://secure.domain (and back, if the user browses back), how can I preserve the session?

Its trivial to pass cookies cross domain using JSONP, but I have no idea what to do with them on the remote side to 'reconnect' to the session.

I have read various things about rolling your own custom session provider, etc. etc. but I haven't found one that is more than just generic advice; certainly no examples of how this might be used to rejoin a session.

This is a for an MVC3 c# web app.

回答1:

Problem with Session's is that they are kept in the same domain.

If you have the 2 applications in sub domains you can always append this to your web.config

<httpCookies domain=".domain.com"/>

and that will do the trick, but if the domains are completely different, the best way is always to roll out your own session provider or use an existing one, like SQL.

You can use for this any Caching System where instead of append variables into a session variable, you append them into the cache as key/value pair, you can always use a NoSQL alternative (plenty of free accounts out there so you can prototyping and make a proof of concept in order to roll out the final bits).

Memcached server is always a good alternative and Couchbase as the community version available for free.

The trick here is to do this:

Cache.AddObject(key + "UserInfo-name", "Bruno Alexandre");

where key could be a query string value appended in global.asax upon session_start

instead of this

Session["UserInfo-name"] = "Bruno Alexandre";


回答2:

When you create cookie then you must write

Response.AppendCookie("Your cookie name");

To get that the code is something like

if (Request.Cookies["Your cookie name"] != null)
{
    string value = Request.Cookies["Your cookie name"].Value;
}

and if there are different solutions then find

machineKey which need to be same. you get it under

system.web in web.config file

and then write after machineKey

 <httpCookies domain=".yourdomainname.com" />


回答3:

I am creating user session using HttpContext from a function.

HttpContext cu;
string username = cu.User.Identity.Name;
username = Guid.NewGuid().ToString();
cu.Session["username"] = username;
HttpCookie hc = new HttpCookie("username", username);
hc.Domain = ".yourdomain.com";
hc.Expires = DateTime.Now.AddDays(1d);
cu.Response.Cookies.Add(hc);

With this code, I am able to share session within 3 sub-domains.