maxence51
maxence51

Reputation: 1054

Asp.Net Core - Prevent Session cookie conflict between same domain applications

I'm using ASP.Net Core 2.2.

By default, session cookie is stored in a cookie named .AspNetCore.Session on a specific domain (e.g: mydomain.com).

In my case I have multiple .net core applications under the domain. mydomain.com/Module1, mydomain.com/Module2, etc...

With this scenario, all the applications share the same cookie for their session. The consequence is that an application try to read the session of the other and generate a warning in the logs:

Error unprotecting the session cookie. System.Security.Cryptography.CryptographicException: The key {...} was not found in the key ring.

Although It's just a warning and session seems to working fine on each application, I wanted to know the proper way to handle this situation.

Thx.

Upvotes: 8

Views: 6905

Answers (2)

mutuma
mutuma

Reputation: 31

When you have .AddAuthentication defined in Startup / ConfigureServices(), to fix this add cookie options this way. Worked for my case.

  services.AddAuthentication(CookieScheme) // Sets the default scheme to cookies
             .AddCookie(CookieScheme, options =>
             {
                 options.LogoutPath = "/logout";
                 options.LoginPath = "/login";
                 options.Cookie = new CookieBuilder()
                 {
                     IsEssential = true,
                     SameSite = SameSiteMode.Lax,
                     SecurePolicy = CookieSecurePolicy.SameAsRequest,
                     Name = ".AspNetCore.Session.yourAppName"
                 };
             });

Upvotes: 0

maxence51
maxence51

Reputation: 1054

A solution that I've found is to change the session cookie name for each application:

In Startup / Configure() :

app.UseSession(new SessionOptions() { Cookie = new CookieBuilder() { 
    Name = ".AspNetCore.Session.MyApp1"}});

Upvotes: 15

Related Questions