
大家好,又见面了,我是你们的朋友全栈君。
在 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);
}
}版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/191993.html原文链接:https://javaforall.cn