在 ASP.NET Core 中替换 ASP.NET machineKey

ASP.NET 中 <machineKey> 元素的实现是可替换的。 这允许通过替换数据保护机制(包括新的数据保护系统)路由对 ASP.NET 加密例程的大多数调用。

包安装

注意

新的数据保护系统只能安装到面向 .NET 4.5.1 或更高版本的现有 ASP.NET 应用程序中。 如果应用程序面向 .NET 4.5 或更低版本,安装将失败。

若要将新的数据保护系统安装到现有的 ASP.NET 4.5.1+ 项目,请安装 Microsoft.AspNetCore.DataProtection.SystemWeb 包。 这将使用默认配置设置实例化数据保护系统。

安装该包时,它会在 Web.config 中插入一行,告诉 ASP.NET 将其用于大多数加密操作,包括 Forms 身份验证、视图状态和对 MachineKey.Protect 的调用。 它不使用数据保护 API。 插入的行如下所示。

<machineKey compatibilityMode="Framework45" dataProtectorType="..." />

提示

你可以通过检查 __VIEWSTATE 等字段来判断新的数据保护系统是否处于活动状态,该字段应以“CfDJ8”开头,如以下示例所示。 “CfDJ8”是“09 F0 C9 F0”magic 标头的 base64 表示形式,该标头用于标识数据保护系统保护的有效负载。

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="CfDJ8AWPr2EQPTBGs3L2GCZOpk...">

包配置

数据保护系统使用默认的零设置配置进行实例化。 但是,由于密钥默认保存在本地文件系统中,因此这不适用于部署在场中的应用程序。 若要解决此问题,可以通过创建子类为 DataProtectionStartup 并替代其 ConfigureServices 方法的类型来提供配置。

下面是自定义数据保护启动类型的示例,它配置了密钥的保存位置和静态加密方式。 它还通过提供自己的应用程序名称来替代默认应用隔离策略。

using System;
using System.IO;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.SystemWeb;
using Microsoft.Extensions.DependencyInjection;

namespace DataProtectionDemo
{
    public class MyDataProtectionStartup : DataProtectionStartup
    {
        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection()
                .SetApplicationName("my-app")
                .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\myapp-keys\"))
                .ProtectKeysWithCertificate("thumbprint");
        }
    }
}

提示

你还可以使用 <machineKey applicationName="my-app" ... /> 来代替对 SetApplicationName 的显式调用。 这种便捷机制可避免强制开发人员创建 DataProtectionStartup 派生类型,适用于开发人员只想设置应用程序名称的情况。

若要启用此自定义配置,请返回 Web.config 并查找包安装添加到配置文件的 <appSettings> 元素。 它将如以下标记所示:

<appSettings>
  <!--
  If you want to customize the behavior of the ASP.NET Core Data Protection stack, set the
  "aspnet:dataProtectionStartupType" switch below to be the fully-qualified name of a
  type which subclasses Microsoft.AspNetCore.DataProtection.SystemWeb.DataProtectionStartup.
  -->
  <add key="aspnet:dataProtectionStartupType" value="" />
</appSettings>

使用刚刚创建的 DataProtectionStartup 派生类型的程序集限定名称填充空白值。 如果应用程序的名称是 DataProtectionDemo,则如下所示。

<add key="aspnet:dataProtectionStartupType"
     value="DataProtectionDemo.MyDataProtectionStartup, DataProtectionDemo" />

现在可以在应用程序中使用新配置的数据保护系统。