迁移 asp.net 核心身份以将数据保护与 SQL 数据库一起使用

Migrate asp.net core Identity to use Data Protection with SQL DB

我有一个 asp.net 核心 3.1 MVC 应用程序,我一直在使用 asp.net 核心身份。现在我创建了一个共享相同源代码的 API,包括身份服务,还创建了用户并发送了一封电子邮件,其中包含待确认的注册令牌。从注册 link,用户被重定向到 MVC 应用程序以完成注册。但是注册时token一直无效

通过阅读其他问题,我看到添加 Microsoft.AspNetCore.DataProtection 包、配置启动 class services.AddDataProtection().PersistKeysToDbContext<MyDbContext>(); 并创建迁移,将使 2 个应用程序共享同一个“实例”机器钥匙"。

配置很简单,我添加了它,但在我看来,我需要在 other 中添加一些密钥才能再次使用身份。添加数据保护后,我的应用程序停止工作,并出现以下错误,似乎它确实缺少 DataProtection 创建的 table 中的一些配置。知道我在这里想念什么吗?我从未创建过机器密钥,所以有点迷茫。 :/

An unhandled exception occurred while processing the request.

ArgumentNullException: Value cannot be null. (Parameter 'source')

Microsoft.EntityFrameworkCore.Utilities.Check.NotNull(T value, string parameterName)

CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information.
Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Protect(byte[] plaintext) System.ArgumentNullException: Value cannot be null. (Parameter 'source') at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AsNoTracking[TEntity](IQueryable`1 source) at Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.EntityFrameworkCoreXmlRepository`1.GetAllElements() at Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.GetAllKeys() at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.CreateCacheableKeyRingCore(DateTimeOffset now, IKey keyJustAdded) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.ICacheableKeyRingProvider.GetCacheableKeyRing(DateTimeOffset now) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.GetCurrentKeyRingCore(DateTime utcNow, Boolean forceRefresh) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.GetCurrentKeyRing() at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Protect(Byte[] plaintext)

我想,我错过了在我的 DbCOntext 中的 DataProtectionKeys 上添加 set; 属性。 public

DbSet<DataProtectionKey> DataProtectionKeys { get; set; }