Reputation: 9561
We have an application that is hosted on multiple domains. Currently we have to deploy to different places with configuration defining the cookie domain. Is there a way to do this all within one application?
The following code is what we're doing within Startup, ConfigureServices
var cookieDomain = Configuration["CookieDomain"];
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Account/LogIn";
options.Cookie.Name = ".SharedCookie";
options.Cookie.Domain = cookieDomain;
options.Cookie.Path = "/";
options.Cookie.HttpOnly = false;
options.Cookie.SameSite = SameSiteMode.None;
});
"mydomain.com" works fine.
"mydomain.com,myotherdomain.com" doesn't work at all (no errors, just returns a cookie with the domain "mydomain.com,myotherdomain.com"
calling ConfigureApplicationCookie twice results in the last taking precedence
Upvotes: 4
Views: 4552
Reputation: 9561
I achieved this by implementing a CookieManager and setting the cookie domain for each request, so it is possible to use the same code deployed to the same place, but using different domains.
var cookieDomain = Configuration["CookieDomain"];
services.ConfigureApplicationCookie(options =>
{
options.CookieManager = new CookieManager();
options.LoginPath = "/Account/LogIn";
options.Cookie.Name = cookieDomain;
options.Cookie.Domain = cookieDomain;
options.Cookie.Path = "/";
options.Cookie.HttpOnly = false;
options.Cookie.SameSite = SameSiteMode.None;
});
public class CookieManager : Microsoft.AspNetCore.Authentication.Cookies.ICookieManager
{
private readonly Microsoft.AspNetCore.Authentication.Cookies.ICookieManager ConcreteManager;
public CookieManager()
{
ConcreteManager = new Microsoft.AspNetCore.Authentication.Cookies.ChunkingCookieManager();
}
public string GetRequestCookie(HttpContext context, string key)
{
return ConcreteManager.GetRequestCookie(context, key);
}
public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
{
options.Domain = context.Request.Host.Value;
ConcreteManager.AppendResponseCookie(context, key, value, options);
}
public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{
options.Domain = context.Request.Host.Value;
ConcreteManager.DeleteCookie(context, key, options);
}
}
Upvotes: 6