消除 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);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM