"Error unprotecting the session cookie" exception
Asked Answered
P

6

29

i have an Asp.NET MVC application with this Authentication setup:

ConfigureServices():

services.AddSession()
services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

Configure():

        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            ClientId = "xx",
            Authority = "xx",
            Events = new OpenIdConnectEvents { OnRemoteFailure = this.OnAuthenticationFailed }
        });

When hosted in IIS, some users get this exception:

Microsoft.AspNetCore.Session.SessionMiddleware, 
      Error unprotecting the session cookie.
System.Security.Cryptography.CryptographicException: The key {9ec59def-874e-45df-9bac-d629f5716a04} was not found in the key ring.
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
   at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
   at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)

I have run this on the hosting server https://github.com/aspnet/DataProtection/blob/dev/Provision-AutoGenKeys.ps1

Web has only HTTPS binding, SSL certificate is ok and signed. What might cause this issue? What actually is that "key" value?

Preponderance answered 29/11, 2016 at 11:39 Comment(7)
Are you running in a the code in multiple instances behind a load balancer? Does this issue only happen in between application restarts?Masculine
@Masculine No load ballancer, no webfarm. Onle one server, one IIS, one site serving all the requests.Omit
I also see a lot of these: warn: Microsoft.AspNetCore.Session.DistributedSession[2] Accessing expired session, Key:67a44622-cea8-dd31-b0af-5b164cbec2caOmit
Does it only happen after an application restart?Masculine
@Masculine No.Omit
Did you ever get this resolved? I am having a similar issue I think.Immunoreaction
My issue was I had not configured the Cookie-based TempData provider. See: learn.microsoft.com/en-us/aspnet/core/fundamentals/app-stateImmunoreaction
S
21

The reason this happens is because multiple ASP sites are hosted on the same machine (hostname). If you make the cookie name unique for each site the conflicts should disappear.

services.AddSession(options => {
    options.IdleTimeout = TimeSpan.FromHours(12);
    options.Cookie.Name = ".yourApp.Session"; // <--- Add line
    options.Cookie.IsEssential = true;
});
Steve answered 19/4, 2022 at 11:15 Comment(4)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Osteotomy
If you can find docs to backup your answer, you should always add the link as a reference at the bottom of the post.Osteotomy
EXPLANATION: you might have more than one app running on the same domain. For example, if you're debugging stuff on localhost:5000 etc. Changing the cookie-name between different apps helps with that.Disappoint
This resolved my issue as well.Archipenko
M
2

In my case I had two instances of the same application running on the same IIS server, under different subdirectories of the Default Web Site. In this situation it's necessary to set the cookie path to the deployment directory, otherwise it just defaults to "/", causing the browser to try and use the same session cookie for both instances. The configuration will look something like this:

    app.UseSession(new SessionOptions()
    {
        Cookie = new CookieBuilder()
        {
            Name = isInstance1 ? ".AspNetCore.Session.MyApp1" : ".AspNetCore.Session.MyApp2",
            Path = isInstance1  ? "/MyApp1" : "/MyApp2"
        }
    });
Morbific answered 23/8, 2023 at 12:51 Comment(0)
K
1

Enable LoadUserProfile in the IIS application pool advanced settings.

Koralle answered 23/10, 2023 at 11:53 Comment(0)
J
0

If you see this error when hosting an application via IIS, try setting "Load User Profile" to "True" in the Application Pool settings.

See Gitlab Issue #8509 - Cryptography Errors

Jordans answered 4/7, 2024 at 10:14 Comment(0)
Z
-2

I had the same issue. I fixed it by :

Startup's ConfigureServices method :

    services.AddControllersWithViews()
            .AddSessionStateTempDataProvider();

    services.AddRazorPages()
            .AddSessionStateTempDataProvider();

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromHours(4);
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.SameSite = SameSiteMode.Strict;
        options.Cookie.HttpOnly = true;
        // Make the session cookie essential if you wish
        //options.Cookie.IsEssential = true;
    });

Startup's Configure method :

        app.UseCookiePolicy();

        app.UseSession();
  • Deleting all existing cookies in browser for this website (or the server may attempt to read old cookies, even if you fix the problem meanwhile)
Zymase answered 30/8, 2021 at 7:44 Comment(0)
N
-5

Change your services.AddSession() for the following:

services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromMinutes(60);
        // You might want to only set the application cookies over a secure connection:
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.SameSite = SameSiteMode.Strict;
        options.Cookie.HttpOnly = true;
        // Make the session cookie essential
        options.Cookie.IsEssential = true;
    });

This should fix your problem!

Net answered 10/10, 2019 at 5:12 Comment(1)
Why does this fix the problem? What was the problem?Quipu

© 2022 - 2025 — McMap. All rights reserved.