public sealed class XmlKeyManager : IKeyManager, IInternalXmlKeyManager
{
public XmlKeyManager(IXmlRepository repository, IAuthenticatedEncryptorConfiguration configuration, IServiceProvider services);
public IKey CreateNewKey(DateTimeOffset activationDate, DateTimeOffset expirationDate);
public IReadOnlyCollection<IKey> GetAllKeys();
public CancellationToken GetCacheExpirationToken();
public void RevokeAllKeys(DateTimeOffset revocationDate, string reason = null);
public void RevokeKey(Guid keyId, string reason = null);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection();
services.AddDataProtection(DataProtectionOptions option);
}
//===========扩展方法如下:
public static class DataProtectionServiceCollectionExtensions
{
public static IDataProtectionBuilder AddDataProtection(this IServiceCollection services);
//具有可传递参数的重载,在集群环境中需要使用此项配置
public static IDataProtectionBuilder AddDataProtection(this IServiceCollection services, Action<DataProtectionOptions> setupAction);
}
// DataProtectionOptions 属性:
public class DataProtectionOptions
{
public string ApplicationDiscriminator { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
//windows dpaip 作为主加密键
.ProtectKeysWithDpapi()
//如果是 windows 8+ 或者windows server2012+ 可以使用此选项(基于Windows DPAPI-NG)
.ProtectKeysWithDpapiNG("SID={current account SID}", DpapiNGProtectionDescriptorFlags.None)
//如果是 windows 8+ 或者windows server2012+ 可以使用此选项(基于证书)
.ProtectKeysWithDpapiNG("CERTIFICATE=HashId:3BCE558E2AD3E0E34A7743EAB5AEA2A9BD2575A0", DpapiNGProtectionDescriptorFlags.None)
//使用证书作为主加密键,目前只有widnows支持,linux还不支持。
.ProtectKeysWithCertificate();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
//windows、Linux、macOS 下可以使用此种方式 保存到文件系统
.PersistKeysToFileSystem(new System.IO.DirectoryInfo("C:\\share_keys\\"))
//windows 下可以使用此种方式 保存到注册表
.PersistKeysToRegistry(Microsoft.Win32.RegistryKey.FromHandle(null))
}
public class RedisXmlRepository : IXmlRepository, IDisposable
{
public static readonly string RedisHashKey = "DataProtectionXmlRepository";
private IConnectionMultiplexer _connection;
private bool _disposed = false;
public RedisXmlRepository(string connectionString, ILogger<RedisXmlRepository> logger)
: this(ConnectionMultiplexer.Connect(connectionString), logger)
{
}
public RedisXmlRepository(IConnectionMultiplexer connection, ILogger<RedisXmlRepository> logger)
{
if (connection == null)
{
throw new ArgumentNullException(nameof(connection));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
this._connection = connection;
this.Logger = logger;
var configuration = Regex.Replace(this._connection.Configuration, @"password\s*=\s*[^,]*", "password=****", RegexOptions.IgnoreCase);
this.Logger.LogDebug("Storing data protection keys in Redis: {RedisConfiguration}", configuration);
}
public ILogger<RedisXmlRepository> Logger { get; private set; }
public void Dispose()
{
this.Dispose(true);
}
public IReadOnlyCollection<XElement> GetAllElements()
{
var database = this._connection.GetDatabase();
var hash = database.HashGetAll(RedisHashKey);
var elements = new List<XElement>();
if (hash == null || hash.Length == 0)
{
return elements.AsReadOnly();
}
foreach (var item in hash.ToStringDictionary())
{
elements.Add(XElement.Parse(item.Value));
}
this.Logger.LogDebug("Read {XmlElementCount} XML elements from Redis.", elements.Count);
return elements.AsReadOnly();
}
public void StoreElement(XElement element, string friendlyName)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
if (string.IsNullOrEmpty(friendlyName))
{
friendlyName = Guid.NewGuid().ToString();
}
this.Logger.LogDebug("Storing XML element with friendly name {XmlElementFriendlyName}.", friendlyName);
this._connection.GetDatabase().HashSet(RedisHashKey, friendlyName, element.ToString());
}
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
if (this._connection != null)
{
this._connection.Close();
this._connection.Dispose();
}
}
this._connection = null;
this._disposed = true;
}
}
}
public static IDataProtectionBuilder PersistKeysToRedis(this IDataProtectionBuilder builder, string redisConnectionString)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (redisConnectionString == null)
{
throw new ArgumentNullException(nameof(redisConnectionString));
}
if (redisConnectionString.Length == 0)
{
throw new ArgumentException("Redis connection string may not be empty.", nameof(redisConnectionString));
}
//因为在services.AddDataProtection()的时候,已经注入了IXmlRepository,所以应该先移除掉
//此处应该封装成为一个方法来调用,为了读者好理解,我就直接写了
for (int i = builder.Services.Count - 1; i >= 0; i--)
{
if (builder.Services[i]?.ServiceType == descriptor.ServiceType)
{
builder.Services.RemoveAt(i);
}
}
var descriptor = ServiceDescriptor.Singleton<IXmlRepository>(services => new RedisXmlRepository(redisConnectionString, services.GetRequiredService<ILogger<RedisXmlRepository>>()))
builder.Services.Add(descriptor);
return builder.Use();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
// ================以下是唯一标识==============
//设置应用程序唯一标识
.SetApplicationName("my_app_sample_identity");
// =============以下是主加密键===============
//windows dpaip 作为主加密键
.ProtectKeysWithDpapi()
//如果是 windows 8+ 或者windows server2012+ 可以使用此选项(基于Windows DPAPI-NG)
.ProtectKeysWithDpapiNG("SID={current account SID}", DpapiNGProtectionDescriptorFlags.None)
//如果是 windows 8+ 或者windows server2012+ 可以使用此选项(基于证书)
.ProtectKeysWithDpapiNG("CERTIFICATE=HashId:3BCE558E2AD3E0E34A7743EAB5AEA2A9BD2575A0", DpapiNGProtectionDescriptorFlags.None)
//使用证书作为主加密键,目前只有widnows支持,linux还不支持。
.ProtectKeysWithCertificate();
// ==============以下是存储位置=================
//windows、Linux、macOS 下可以使用此种方式 保存到文件系统
.PersistKeysToFileSystem(new System.IO.DirectoryInfo("C:\\share_keys\\"))
//windows 下可以使用此种方式 保存到注册表
.PersistKeysToRegistry(Microsoft.Win32.RegistryKey.FromHandle(null))
// 存储到redis
.PersistKeysToRedis(Configuration.Section["RedisConnection"])
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-3 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2026 源码网商城 (www.yuanmawang.com) 版权所有