Search code examples
c#asp.net-coresessioniisasp.net-core-mvc

The session cookie cannot be unprotected when ASP.NET Core 8.0 Web App runs on IIS


Once the below configuration is added to Startup.cs of an ASP.NET Core MVC Web Application targeting .NET 8.0:

services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(50);
    options.Cookie.IsEssential = true;
    options.Cookie.HttpOnly = true;                
    options.Cookie.SameSite = SameSiteMode.Strict;
});

...

app.UseSession();

hundreds such warnings are logged by the application deployed to an IIS 8.5 server (Windows Server 2012 R2):

https://example.com/Login: Error unprotecting the session cookie.

Logger: Microsoft.AspNetCore.Session.SessionMiddleware

Callsite: Microsoft.AspNetCore.Session.CookieProtection.Unprotect

Exception: System.Security.Cryptography.CryptographicException: The key {x-y-z} was not found in the key ring. For more information go to https://aka.ms/aspnet/dataprotectionwarning at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

Session is only used to store a list of announcements to show to the user once he logs in:

[HttpPost]
public async Task<IActionResult> Login(...)
{
   ...
   await announcementService.BuildAnnouncementsFor(user);
   ...
}

Ultimately, BuildAnnoucementsFor stores a list of announcements (i.e. strings) to session using IHttpContextAccessor.HttpContext.Session, which is configured as following:

services.AddHttpContextAccessor();

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

I've already configured User Profile to be loaded in IIS configuration since DataProtection seems to be related to the problem and when the application pool was (re)started the bellow warning was also logged:

Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.

The above had the latter warning go away but SessionMiddleware still warns about the encryption key not found in the key ring. Indeed, the keys reported in the warnings are not in the C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder, where IIS looks for keys, by default.

I would very much like to have those warnings go away but I don't know what else needs to be configured either in code or in IIS.


Solution

  • After having applied various configuration combinations and testing I think I should answer my own question.

    To have Session cookie work properly for an ASP.NET Core 8 MVC Web Application hosted in IIS 8.5 on Windows Server 20212 R2, make sure:

    services.AddSession(options => {
      ...
      options.Cookie.Name = ".yourApp.Session";
      ...
    });
    

    Hope it helps.