如何在 ASP.NET Core 2.0 中实现 machineKey

How to implement machineKey in ASP.NET Core 2.0

在 ASP.NET(非核心)中,我通常会向 web.config 添加一个 machineKey,这样我就可以在本地机器而不是服务器上执行一些功能,这样 database/callback操作将使用相同的密钥。例如

<system.web>
  <machineKey validationKey="*********" 
              decryptionKey="*********" 
              validation="HMACSHA256" 
              decryption="AES" />
</system.web>

有人可以建议如何在 ASP.NET Core 2.0 中完成此操作吗?

您现在需要使用DataProtection APis

The ASP.NET Core data protection stack provide a simple, easy to use cryptographic API a developer can use to protect data, including key management and rotation.

示例可以在官方 DataProtection repo.

中找到

顺便说一下,同样的方法也适用于 ASP.NET:Replacing <machineKey> in ASP.NET


数据保护系统建立在两个核心概念之上——数据保护提供者(由IDataProtectionProvider接口表示),用于创建数据保护器(由IDataProtector接口表示) ) 通过 CreateProtector 方法。数据保护器用于加密和解密数据。

要将 IDataProtectionProvider 注册到 DI 使用 .AddDataProtection 方法:

public void ConfigureServices(IServiceCollection services)
{
    // Adds data protection services
    services.AddDataProtection();
    ...
}

对于您想基于一些负责生成身份验证 cookie 的经典 ASP.NET 应用程序构建 ASP.NET 核心应用程序的遗留用途,有一个开源库可用,它可以启用您将这些遗留 cookie 用于您的 ASP.NET 核心应用程序。开发人员使用 .NET Framework 参考实现来构建他们自己的基于 encryption/decryption 逻辑的 Machinekey。参见 https://github.com/synercoder/FormsAuthentication

您可以在 https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-storage-providers?view=aspnetcore-2.2&tabs=visual-studio

找到很好的示例

我使用我的数据库上下文在多个实例中保留密钥。

DbContext.cs

public class MyContext : IDataProtectionKeyContext
{
  ...
  // This maps to the table that stores keys.
  public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddDataProtection().PersistKeysToDbContext<MyContext>();
}

asp.net Core 你应该设置数据保护系统。

有关详细信息,请阅读 this answer