如何在 ASP.NET Core 中的子域之间共享会话?

How can I share session among subdomains in ASP.NET Core?

我的网站有 ali.sarahah.com 等子域,但如果用户从 www.sarahah.com 登录,然后转到 ali.sarahah.com 会话未保存。搜索后我在 Startup.cs 中添加了以下内容:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    CookieDomain = ".sarahah.com"
});

我发现 .AspNetCore.Identity.Application cookie 域仍然显示子域而不是域,会话问题仍然存在。

我是不是做错了什么?

我认为您需要删除域分配中的前导 .,如本 GitHub 问题所述:

app.UseCookieAuthentication(
    new CookieAuthenticationOptions
    {
        // Note that there is no leading .
        CookieDomain = "sarahah.com",
        CookieSecure = CookieSecurePolicy.None
    });

有关各种属性,请参阅 CookieAuthenticationOptions

我可以通过将此添加到 Startup.cs 中的 ConfigureServices 方法来解决它:

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.Cookies.ApplicationCookie.CookieDomain = ".yourdomain.com";
            options.Cookies.ApplicationCookie.CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.None;
        })

CookieSecure 部分是因为我的网站在不同页面的 http 和 https 之间移动。

谢谢:)

以防有人使用 ASP.NET Core 2.0 寻找此问题的解决方案。添加身份验证服务时,您可以通过 ConfigureServices 方法中的 CookieAuthenticationOptions 设置 cookie 域。

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Cookie.Domain = ".yourdomain.com";
        });