在两个 ASP.NET Core 应用程序之间共享 Cookie

Rya*_*ing 5 c# asp.net-core-mvc asp.net-core asp.net-core-2.0

我在两个单独的 ASP.NET Core 项目中使用WsFederation 。

每个项目都有以下内容Startup.cs

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
})
.AddWsFederation(options =>
{
    options.Wtrealm = Configuration["Wtrealm"];
    options.MetadataAddress = "http://example.com/metadata.xml";
    options.SkipUnrecognizedRequests = true;
    options.RequireHttpsMetadata = false;
    options.UseTokenLifetime = false;
})
.AddCookie(options =>
{
    options.Cookie.Name = "MySharedCookie";
    options.Cookie.Path = "/";
    options.Cookie.Domain = ".dev.example.com";
});
Run Code Online (Sandbox Code Playgroud)

我在浏览器中加载项目 #1,并得到我的 cookie:

在此输入图像描述

然后,我导航到同一子域上的项目#2。但是,项目 #2 无法识别MySharedCookie并重新进行身份验证。我得到一个具有相同名称但不同值的新 cookie:

在此输入图像描述

我想做的事情在 ASP.NET Core 中可行吗?在 ASP.NET Core 中有没有办法可以与项目 #2 共享项目 #1 的 cookie?

Mar*_*eur 4

这记录在使用 ASP.NET 和 ASP.NET Core 在应用程序之间共享 cookie。还有一个Cookie 共享应用程序示例可用。

为了共享 cookie,您需要DataProtectionProvider在每个应用程序中创建 cookie,并在应用程序之间使用一组通用/共享的密钥。

.AddCookie(options =>
{
    options.Cookie.Name = ".SharedCookie";
    options.Cookie.Domain = "example.com";
    options.DataProtectionProvider =
        DataProtectionProvider.Create(new DirectoryInfo("path-tokeys"));
});
Run Code Online (Sandbox Code Playgroud)

  • 或者更好的是,配置数据保护服务:https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?tabs=aspnetcore2x#persistkeystofilesystem services.AddDataProtection() .PersistKeysToFileSystem (new DirectoryInfo(@"\\服务器\共享\目录\")); (4认同)