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

在 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);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值