您现在的位置是: 首页 > .NET CORE > 文章详情 文章详情
消除 ASP.NET Core 告警 "No XML encryptor configured. Key may be persisted to storage in unencrypted form
2019-08-19 【.NET CORE】 2646人浏览
在 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)
相关文章

热门收藏
- .net core Redis分布式缓存的客户端实现
- .net core API 统一拦截错误
- ASP.NET Core MVC中的IActionFilter.OnActionExecuted方法执行时,Controller中Action返回的对象是否已经输出到Http Response中
- aspnet core 2.1中使用jwt从原理到精通一
- aspnet core 2.1中使用jwt从原理到精通二
- aspnet core 2.1中使用jwt从原理到精通三
- ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统
- 消除 ASP.NET Core 告警 "No XML encryptor configured. Key may be persisted to storage in unencrypted form
- .NET Core 中基于 IHostedService 实现后台定时任务
- 【.Net Core】获取绝对路径、相对路径