反序列化令牌时抛出异常。无法在 .Net Core 2.2 应用程序中解密防伪令牌

Kee*_*arn 10 c# antiforgerytoken asp.net-core

我的日志中出现错误。我花了一天的大部分时间来寻找解决方案,但找不到满足我要求的解决方案。

这是日志错误

Severity=[ERROR], ipaddress=xxxx, subprocess=Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery, description=反序列化令牌时抛出异常。Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException:无法解密防伪令牌。---> System.Security.Cryptography.CryptographicException: 在密钥环中找不到密钥 {xxxxxxxxxx}。在 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) 在 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) ) 在 Microsoft.AspNetCore.DataProtection.KeyManagement。

    "Certificates": {
    "StoreName": "My",
    "StoreLocation": "LocalMachine"
    "SerialNumber": "xxxxxxxxxxxx"
},
   
   private X509Certificate2 LCertificate()
    {
        var storeName = Configuration["Certificates:StoreName"];
        var storeLocation = Configuration["Certificates:StoreLocation"];
        string serialNumber = Configuration["Certificates: SerialNumber"];
        using(X509Store store = new X509Store(storeName,storeLocation))
        {
            var certificates = store.Certificates
                                    .Find(X509FindType.FindBySerialNumber,
                                          serialNumber,
                                          acceptValidCertOnly);             

            return certificates[0];
        }
    }
    
     public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentityServer
                .AddSigningCredential(new X509Certificate2(LCertificate()))
      
    }

   [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginModel model)
    {
Run Code Online (Sandbox Code Playgroud)

Roa*_* S. 9

如果

  • 您的应用托管在多台服务器上
  • 尚未配置共享数据保护
  • 你没有使用粘性会话

当用户从服务器 A 请求带有表单的页面,然后将表单提交给服务器 B 时,就会发生这种情况。

它也可能发生在单个 IIS 服务器上,如果

  • 用户请求带有表单的页面
  • 你重启服务器
  • 用户提交表单

原因是重启导致新的密钥环加载到内存中,并且表单内的防伪密钥不再有效。

后一种情况可以在 IIS 中通过检查应用程序池中的“加载用户配置文件”来修复。

更多信息:https : //docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-3.1