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

5

我在两个独立的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";
});

我在浏览器中加载项目 #1,然后获取我的 cookie:

enter image description here

我然后导航到同一子域下的项目2。但是,项目2不认识MySharedCookie并且重新验证身份。我得到了一个具有相同名称但不同值的新cookie:

enter image description here

在ASP.NET Core中,我想做的事情是否可行?在ASP.NET Core中,我是否可以将项目#1的cookie与项目#2共享?

也许这个链接可以帮到你:https://dev59.com/HWMl5IYBdhLWcg3wVltf - DOMZE
1
他们还必须共享他们的数据保护密钥。 - Tratcher
1个回答

4
这在ASP.NET 和 ASP.NET Core中共享cookie文档中有详细说明。此外,还提供了一个Cookie共享应用程序示例
要实现cookie共享,您需要在每个应用程序中创建一个DataProtectionProvider,并使用共享的密钥集来处理。
.AddCookie(options =>
{
    options.Cookie.Name = ".SharedCookie";
    options.Cookie.Domain = "example.com";
    options.DataProtectionProvider =
        DataProtectionProvider.Create(new DirectoryInfo("path-tokeys"));
});

4
更好的方式是配置数据保护服务:https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?tabs=aspnetcore2x#persistkeystofilesystem services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(@"\server\share\directory")); - Tratcher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接