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

时间:2017-01-26 11:31:36

标签: c# cookies asp.net-core asp.net-core-mvc middleware

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

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

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

我做错了吗?

3 个答案:

答案 0 :(得分:7)

我认为您需要删除域名分配中的前导.,详见此GitHub问题:

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

有关各种属性,请参阅CookieAuthenticationOptions

答案 1 :(得分:2)

我能够通过将它添加到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之间移动。

谢谢:)

答案 2 :(得分:2)

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

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