您现在的位置是: 首页 >  .NET CORE >  文章详情 文章详情

消除 ASP.NET Core 告警 "No XML encryptor configured. Key may be persisted to storage in unencrypted form

2019-08-19 【.NET CORE】 2520人浏览

在 ASP.NET Core 中如果在 DataProtection 中使用了 PersistKeysToFileSystem 或 PersistKeysToFileSystem

services.AddDataProtection().PersistKeysToFileSystem();
services.AddDataProtection().PersistKeysToRedis();

会在日志中出现下面的告警:

warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {08f8b6bf-e57a-440b-9fa7-39f319725b58} may be persisted to storage in unencrypted form.

这是由于 DataProtection 所用到的密钥本身没有被加密存储,要消除这个告警,需要一个专门用来加密“密钥”的密钥。

首先用 openssl 命令创建密钥,得到 cnblogs.pfx 文件

# openssl req -x509 -newkey rsa:4096 -sha256 -nodes -keyout cnblogs.key -out cnblogs.crt -subj "/CN=cnblogs.com" -days 3650# openssl pkcs12 -export -out cnblogs.pfx -inkey cnblogs.key -in cnblogs.crt -certfile cnblogs.crt -passout pass:

然后在 .csproj 项目文件中添加资源文件 Resource.resx ,将 cnblogs.pfx 添加到 Resource.resx ,并将 "Build Action" 设置为 “Embedded resource” 。


  
  

最后在 Startup 中添加下面的代码就可以成功消除告警。

public void ConfigureServices(IServiceCollection services){    //..
    services.AddDataProtection()
        .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"./"))
        .ProtectKeysWithCertificate(GetCertificate());
}private X509Certificate2 GetCertificate(){    var assembly = typeof(Startup).GetTypeInfo().Assembly;    using (var stream = assembly.GetManifestResourceStream(
        assembly.GetManifestResourceNames().First(r => r.EndsWith("cnblogs.pfx"))))
    {        if (stream == null)            throw new ArgumentNullException(nameof(stream));        var bytes = new byte[stream.Length];
        stream.Read(bytes, 0, bytes.Length);        return new X509Certificate2(bytes);
    }
}



很赞哦! (0)

站长推荐