.net核心中是否可以支持多个cookie域?

时间:2018-08-16 09:54:25

标签: cookies asp.net-core .net-core asp.net-core-2.0

我们有一个托管在多个域中的应用程序。当前,我们必须使用定义cookie域的配置来部署到其他地方。有没有办法在一个应用程序中完成所有这些工作?

以下代码是我们在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”工作正常。

“ mydomain.com,myotherdomain.com”根本不起作用(没有错误,仅返回域为“ mydomain.com,myotherdomain.com”的cookie。

两次调用ConfigureApplicationCookie将导致最后一个优先级

1 个答案:

答案 0 :(得分:0)

我通过实现CookieManager并为每个请求设置cookie域来实现这一目标,因此可以使用部署到相同位置的相同代码,但使用不同的域。

        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);
    }
}