0
votes

I have 2 Asp.Net Core 2.2 applications and I want to share session between them. I've set up session in a SQL database and both connect ok. They are on different sub domains. I understand that I can set the Cookie.Domain the startup file, which would solve the problem at a basic level, so each application would create the cookie such that it can be accessed. e.g.

Domain 1. "www.website.com" Domain 2. "dashboard.website.com" At present these sites can't access each others session cookie.

If I set the domain cookie to ".website.com", both should be able to access this.

The problem is that we have multiple domains that use this website, so it could be:

www.domain1.com
dashboard.domain1.com

www.domain2.com
dashboard.domain2.com

www.domain3.com
dashboard.domain3.com

I need to be able to inject the current host name into the startup cookie domain, in order to have it dynamically set, depending on the domain of the active website.

Is this at all possible?

Just to clarify, www.domain1.com does not need to be able to access www.domain2.com. Only the www. and dashboard. variations of each domain need to be able to connect to each other.

Thanks in advance, David

1
I believe this is for the authorization cookie, as opposed to a session cookie? - David Hendrick

1 Answers

1
votes

To share sessions across applications, you need only follow the directions in the docs. It basically boils down to two things:

  1. You need to persist the data protection keys to a common store that all the apps can access. A UNC path will do, or you can even use something like Azure Key Vault.

  2. You need to set a common application name. Data protection values are segregated by application by default. Setting a custom name, which is then used across all the apps allows them to all access the same set of data.

As far as setting the cookie domain goes. There's no good way to do this by convention. The actual domain name is only available in the context of the request pipeline, which is not available to you in something like Startup (there's no request). Even if you could, it's not reliable anyways. In situations where you have a reverse proxy or, importantly , when hosting in containers, the domain will be localhost, since the actual domain isn't applied directly to the app.

Long and short, your best bet is to use configuration. You can, for example, have environment-specific JSON files like appsettings.Domain1.json, appsettings.Domain2.json, etc. Inside each, you can add a something like:

{
    "CookieDomain": ".domain1.com"
}

Then, when you deploy, you set the environment to the appropriate domain, and that config file will be used. In Startup, you'd just do:

services.ConfigureApplicationCookie(o => {
    o.Cookie.Domain = Configuration["CookieDomain"];
});