在两个 ASP.NET Core 应用程序之间共享 Cookie [英] Sharing Cookies Between Two ASP.NET Core Applications

查看:27
本文介绍了在两个 ASP.NET Core 应用程序之间共享 Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个单独的 ASP.NET 中使用

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

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

解决方案

这记录在 使用 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"));});

I'm using WsFederation in two separate ASP.NET Core projects.

Each project has the following in 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";
});

I load project #1 in the browser and I get my cookie:

I then navigate to project #2 on the same sub domain. However, project #2 doesn't recognize MySharedCookie and re-authenticates. I get a new cookie with the same name but a different value:

Is what I'm trying to do possible in ASP.NET Core? Is there a way in ASP.NET Core I can share project #1's cookie with project #2?

解决方案

This is documented at Sharing cookies among apps with ASP.NET and ASP.NET Core. There is also a Cookie Sharing App Sample available.

In order to share cookies, you create a DataProtectionProvider in each app and using a common/shared set of keys between the apps.

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

这篇关于在两个 ASP.NET Core 应用程序之间共享 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆