是否可以在ASP.NET Core中禁用数据保护加密?

时间:2019-04-26 22:07:38

标签: c# 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.

我在Google上搜索了很多,似乎解决此问题的“正确”方法是使用.PersistKeysToFileSystem()合并加密密钥。但是有替代方法吗?例如完全禁用加密/数据保护?

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

1 个答案:

答案 0 :(得分:0)

数据保护堆栈是必需的,用于保护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#azure-and-redis

以下文档资源也很不错: