Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

c# - Sharing Cookies Between Two ASP.NET Core Applications

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:

enter image description here

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:

enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"));
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...