DataProtection/WebApp01/CustomDataProtection/DataProtectionExtensions.cs
(开头部分) 4KB这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。
namespace WebApp01.CustomDataProtection
{
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
public static class DataProtectionExtensions
{
/// <summary>注册数据保护服务,使用x509证书加密</summary>
/// <param name="services">The services.</param>
/// <returns></returns>
/// <exception cref="Exception">not found X509Certificate</exception>
public static IDataProtector AddDataProtectionWithX509(this IServiceCollection services)
{
ServiceProvider provider = services.BuildServiceProvider();
// 获取用户配置数据保护的Option
ProtectionOption protectionOption = provider
.GetRequiredService<IOptions<ProtectionOption>>().Value;
// 获取证书
X509Certificate2 cert = GetCertificateFromStore(protectionOption.Thumbprint);
// 注册服务
services.AddDataProtection()
// 设置应用程序名称
.SetApplicationName(protectionOption.ApplicationName)
// 设置秘钥存储路径
.PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + "//" + protectionOption.SecretKeyPath))
// 设置用于加密的证书
.UnprotectKeysWithAnyCertificate(cert);
provider = services.BuildServiceProvider();
IDataProtectionProvider protectionProvider = provider.GetRequiredService<IDataProtectionProvider>();
// 创建数据保护器
IDataProtector protector = protectionProvider.CreateProtector(protectionOption.Purpose);
// 注册单例的数据保护器
services.AddSingleton<IDataProtector>(serviceProvider => protector);
return protector;
}
public static IServiceCollection ProtectedConfigure<TOptions>(this IServiceCollection services
, IConfigurationSection section)
where TOptions : ProtectionOptionBase, new()
{
ServiceProvider provider = services.BuildServiceProvider();
IDataProtector protector = provider.GetRequiredService<IDataProtector>();
services.Configure<TOptions>(option =>
{
var config = section.Get<TOptions>();
后面还有 63 行代码,解锁后查看完整代码
24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明
AI 解读
登录后可用,每次 10 积分,解读结果公开显示在下面。
还没有人解读过这个文件。
