菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
458
0

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

原创
05/13 14:22
阅读数 11177

在 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” 。

<ItemGroup>
  <None Remove="Resources\cnblogs.pfx" />
</ItemGroup>

<ItemGroup>
  <EmbeddedResource Include="Resources\cnblogs.pfx" />
</ItemGroup>

最后在 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/200
458 点赞
0 评论
收藏
为你推荐 换一批