"错误取消保护会话cookie"异常

Sko*_*šek 5 authentication iis asp.net-core

我有一个Asp.NET MVC应用程序与此身份验证设置:

ConfigureServices():

services.AddSession()
services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
Run Code Online (Sandbox Code Playgroud)

配置():

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

在IIS中托管时,某些用户会收到此异常:

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)
Run Code Online (Sandbox Code Playgroud)

我在托管服务器上运行了这个https://github.com/aspnet/DataProtection/blob/dev/Provision-AutoGenKeys.ps1

Web只有HTTPS绑定,SSL证书可以签名.什么可能导致这个问题?究竟是什么"关键"价值?

Zan*_*lal 15

发生这种情况的原因是因为多个 ASP 站点托管在同一台计算机(主机名)上。如果您使每个站点的 cookie 名称都是唯一的,则冲突应该会消失。

services.AddSession(options => {
    options.IdleTimeout = TimeSpan.FromHours(12);
    options.Cookie.Name = ".yourApp.Session"; // <--- Add line
    options.Cookie.IsEssential = true;
});
Run Code Online (Sandbox Code Playgroud)

  • 通过添加更多有关代码的作用以及它如何帮助操作员的信息,可以改进您的答案。 (3认同)
  • 说明:您可能有多个应用程序在同一域上运行。例如,如果您正在“localhost:5000”等上调试内容。更改不同应用程序之间的 cookie 名称会对此有所帮助。 (2认同)

小智 -4

将 services.AddSession() 更改为以下内容:

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;
    });
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题!

  • 为什么这可以解决问题?问题出在哪里? (6认同)