Session id always changing for ASP.NET Core + Redis + nginx

I actually cannot reproduce the problem on a mac with the configuration (2 local servers load balanced via nginx and connected to the same local redis distributed cache)

Anyways, if applicable, have you tried enabled ip_hash in nginx upstream module ?

From the sessions persistance section in nginx doc:

If there is the need to tie a client to a particular application server — in other words, make the client’s session “sticky” or “persistent” in terms of always trying to select a particular server — the ip-hash load balancing mechanism can be used.

upstream study_server{
    ip_hash;
    server localhost:8011 weight=1;
    server localhost:8013 weight=1;
    #server localhost:8014 weight=1;
    #server 172.17.16.147:8012 weight=2;
    #server 172.17.16.147:8011 weight=2;
}

If that's not solving your issue please have a look at similar issues on stack exchange:

  • https://serverfault.com/questions/133500/nginx-sticky-session-and-iis

  • ASP.NET: Session.SessionID changes between requests


If the CheckConsentNeeded property is assigned with true, the application will not set any non-essential cookie without user consent. This includes the session cookie, which is non-essential by default.

There are at least three solutions to your problem:

  1. You can set CheckConsentNeeded to false.
    ...

    options.CheckConsentNeeded = context => false;

    ...

This will disable the whole cookie consent feature.

  1. You can mark the session cookie as essential.
    ...

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(100);
        options.Cookie.IsEssential = true;
    });

    ...

This will allow the application to set the session cookie regardless of user's consent.

  1. You can leave everything as it is now. In this case the session will start only after the user clicks the "Accept" button on the cookie use policy popup.

Solved it by using

var redis = ConnectionMultiplexer.Connect("<REDIS URI>");

services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Keys");

Article:

https://onecodex.ch/blogsdotnetcoredistributed-redis-cache/

Necessary package: https://www.nuget.org/packages/Microsoft.AspNetCore.DataProtection.Redis/