如何在所有子域中保留身份验证 cookie?

How to persist authentication cookie throughout all subdomains?

所以我完成了从 aspnetcore1.1 到 aspnetcore2.0 的迁移,并且正在努力处理 Startup.cs 中的新身份验证设置。

我的所有网站共享同一个域“.example.com”。用户使用他们的 Google 帐户登录,然后收到一个应用程序 cookie,我想在“.example.com”的所有子域中保留它。

虽然现在,当用户登录时,cookie 已成功创建,但是他们会从域中的所有其他站点注销。有人可以尝试一下吗?

public void ConfigureServices (IServiceCollection services)
{
    // ...-snip-...

    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.Name = ".AuthCookie";
        options.Cookie.Expiration = TimeSpan.FromDays(7);
        options.LoginPath = "/Account/Login";
        options.Cookie.Domain = ".example.com";
    });

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
       .AddGoogle(options => { /* ...-snip...- */ });

    // ...-snip-...
}

public void Configure (IApplicationBuilder app)
{
    // ...-snip-...

    app.UseAuthentication();

    // ...-snip-...
}

我的所有应用程序都在其 Startup.cs 文件中共享相同的代码。跟使用CookieAuthenticationDefaults有关系吗?还是我的 ConfigureApplicationCookie 中遗漏了什么?

知道了!看来我需要创建一个数据保护提供程序 to share authentication cookies between applications。以下是工作代码更改:

services.ConfigureApplicationCookie(options =>
{
    var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"));

    options.Cookie.Name = ".AuthCookie";
    options.Cookie.Expiration = TimeSpan.FromDays(7);
    options.LoginPath = "/Account/Login";
    options.Cookie.Domain = ".example.com";
    options.DataProtectionProvider = protectionProvider;
    options.TicketDataFormat = new TicketDataFormat(protectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2"));
});