首页 > 解决方案 > 是否可以禁用 ASP.NET Core 中的数据保护加密?

问题描述

最初在 中Startup.cs,我们完全省略了AddDataProtection()调用。当我们尝试部署应用程序时,我们看到了:

System.Security.Cryptography.CryptographicException: The key {...} 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)
warn: Microsoft.AspNetCore.Session.SessionMiddleware[7]
      Error unprotecting the session cookie.

当我添加services.AddData.AddDataProtection().SetApplicationName("MyAppName");到时ConfigureServices(),我们现在看到部署后

System.Exception: An error was encountered while handling the remote login. ---> System.Exception: Correlation failed.
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)
warn: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[15]
      '.AspNetCore.Correlation.OpenIdConnect.{SomeWeirdString}' cookie not found.

我用谷歌搜索了很多,似乎解决这个问题的“正确”方法是将加密密钥与.PersistKeysToFileSystem(). 有没有替代方案?例如完全禁用加密/数据保护?

对于某些背景,这个应用程序是我们从 ASP.NET 迁移到 ASP.NET Core 的最后阶段,之前我们将会话状态存储在 Redis 中,没有加密。

标签: c#asp.net-core

解决方案


数据保护堆栈是必需的,用于保护 cookie、会话状态、临时数据等中的数据。数据保护将密钥保存在某处以加密和解密数据。有几个选项可以保留密钥 - 默认情况下,使用文件系统或注册表。在 IIS 或 Azure 中的本地服务器上托管时,它通常可以正常工作。对于其他部署选项,尤其是使用容器,您通常必须执行一些配置。例如,容器通常具有临时存储,因此部署新容器实例后加密密钥会丢失。

正如您提到的 Redis,我建议您查看 Redis 密钥存储提供程序:https ://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-storage-providers?view= aspnetcore-2.2&tabs=visual-studio#redis

以下文档资源也值得一读:


推荐阅读