In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to configure ASP.NETCore data protection DataProtection cluster scenario. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it with the editor.
Encryption extension
IAuthenticatedEncryptor and IAuthenticatedEncryptorDescriptor
IAuthenticatedEncryptor is a basic interface for Data Protection in building its cryptographic encryption system.
In general, a key corresponds to an IAuthenticatedEncryptor,IAuthenticatedEncryptor that encapsulates the key materials and necessary encryption algorithm information that need to be used in encryption operations.
Here are two api methods provided by the IAuthenticatedEncryptor interface:
Decrypt (ArraySegment ciphertext, ArraySegment additionalAuthenticatedData): byte []
Encrypt (ArraySegment plaintext, ArraySegment additionalAuthenticatedData): byte []
The parameter additionalAuthenticatedData in the interface represents some of the ancillary information provided when building the encryption.
The IAuthenticatedEncryptorDescriptor interface provides a method for creating an IAuthenticatedEncryptor instance that contains type information.
CreateEncryptorInstance (): IAuthenticatedEncryptor
ExportToXml (): XmlSerializedDescriptorInfo
Key management extension
In key system management, a basic interface IKey is provided, which contains the following properties:
Activation
Creation
Expiration dates
Revocation status
Key identifier (a GUID)
IKey also provides a method CreateEncryptorInstance to create an instance of IAuthenticatedEncryptor.
The IKeyManager interface provides a series of methods for manipulating Key, including storage, retrieval operations, and so on. The advanced operations he provides are:
Create a Key and persist it
Get all the Key from the repository
Undo one or more keys saved to storage
XmlKeyManager
In general, developers do not need to implement IKeyManager to customize a KeyManager. We can use the XmlKeyManager class provided by the system by default.
XMLKeyManager is a class that specifically implements IKeyManager and provides some very useful methods.
Public sealed class XmlKeyManager: IKeyManager, IInternalXmlKeyManager {public XmlKeyManager (IXmlRepository repository, IAuthenticatedEncryptorConfiguration configuration, IServiceProvider services); public IKey CreateNewKey (DateTimeOffset activationDate, DateTimeOffset expirationDate); public IReadOnlyCollection GetAllKeys (); public CancellationToken GetCacheExpirationToken (); public void RevokeAllKeys (DateTimeOffset revocationDate, string reason = null); public void RevokeKey (Guid keyId, string reason = null);}
IAuthenticatedEncryptorConfiguration mainly specifies the algorithm used by the new Key.
IXmlRepository mainly controls where Key is persisted.
IXmlRepository
The IXmlRepository interface mainly provides methods to persist and retrieve XML, as long as it provides two API:
GetAllElements (): IReadOnlyCollection
StoreElement (XElement element, string friendlyName)
We can define the storage location of the data protection xml by implementing the StoreElement method of the IXmlRepository interface.
GetAllElements to retrieve all existing encrypted xml files.
This is the end of the interface section, because in this article I want to focus on the following. Let's go to the official documentation for more introduction to the interface.
Cluster scene
The API above probably looks a little boring, so let's see what we need to do with Data Protection in a cluster scenario.
As I mentioned at the end of the summary of the previous article, when doing distributed clusters, we need to know some of the mechanisms of Data Protection, because if you do not understand these may cause some trouble for your deployment, let's take a look.
When doing clustering, we must know and understand three things about ASP.NET Core Data Protection:
1. Program recognizer
Application discriminator, which is used to identify the uniqueness of the application.
Why do you need this thing? Because in the cluster environment, if it is not limited by the specific hardware machine environment, it is necessary to eliminate some differences between running machines, and some specific identities need to be abstracted. to identify the application itself and use the identity to distinguish different applications. At this point, we can specify ApplicationDiscriminator.
In services.AddDataProtection (DataProtectionOptions option), ApplicationDiscriminator can be passed as a parameter. Take a look at the code:
Public void ConfigureServices (IServiceCollection services) {services.AddDataProtection (); services.AddDataProtection (DataProtectionOptions option);} / = the extension method is as follows: public static class DataProtectionServiceCollectionExtensions {public static IDataProtectionBuilder AddDataProtection (this IServiceCollection services); / / overloading with transferable parameters, which is required to configure public static IDataProtectionBuilder AddDataProtection (this IServiceCollection services, Action setupAction) in a cluster environment;} / / DataProtectionOptions attribute: public class DataProtectionOptions {public string ApplicationDiscriminator {get; set;}}
You can see that this extension returns an IDataProtectionBuilder, and there is also an extension method called SetApplicationName in IDataProtectionBuilder, which internally still modifies the value of ApplicationDiscriminator. That is to say, the following words are equivalent:
Services.AddDataProtection (x = > x.ApplicationDiscriminator = "my_app_sample_identity")
Services.AddDataProtection () .SetApplicationName (my_app_sample_identity)
In other words, the same application in a cluster environment needs to be set to the same value (ApplicationName or ApplicationDiscriminator).
2. Main encryption key
"Master encryption key" is mainly used for encryption and decryption, including some session data and status of a client server in the process of request. There are several options that can be configured, such as using certificates or windows DPAPI or the registry. If it is a non-windows platform, the registry and Windows DPAPI cannot be used.
Public void ConfigureServices (IServiceCollection services) {services.AddDataProtection () / / windows dpaip as the primary encryption key .ProtectKeysWithDpapi () / this option can be used for windows 8 + or windows server2012+ (based on Windows DPAPI-NG) .ProtectKeysWithDpapiNG ("SID= {current account SID}", DpapiNGProtectionDescriptorFlags.None) / / for windows 8 + or windows server2012+ can use this option (certificate based) .ProtectKeysWithDpapiNG ("CERTIFICATE=HashId:3BCE558E2AD3E0E34A7743EAB5AEA2A9BD2575A0", DpapiNGProtectionDescriptorFlags.None) / use a certificate as the primary encryption key Currently, it is only supported by widnows, but not by linux. .ProtectKeysWithCertificate ();}
If they are in a clustered environment, they need to have the same primary encryption key configured.
3. Storage location after encryption
As mentioned in the previous article, Data Protection generates xml files to store session or state key files by default. These files are used to encrypt or decrypt state data such as session.
This is the location where the private key is stored in the previous article:
1. If the program is hosted under Microsoft Azure, it is stored in the "% HOME%\ ASP.NET\ DataProtection-Keys" folder.
2. If the program is hosted under IIS, it is stored in the ACLed special registry key of the HKLM registry, and only the worker process can access it. It uses windows's DPAPI encryption.
3. If the current user is available, that is, win10 or win7, it is stored in the "% LOCALAPPDATA%\ ASP.NET\ DataProtection-Keys" folder, which also uses windows's DPAPI encryption.
4. If none of these match, then the private key is not persisted, that is, when the process shuts down, the generated private key is lost.
In a cluster environment:
The easiest way is through file sharing, DPAPI, or the registry, which means that encrypted xml files are stored in the same place. Why is it the easiest? because the system has been packaged, there is no need to write extra code, but make sure that the ports related to file sharing are open. As follows:
Public void ConfigureServices (IServiceCollection services) {services.AddDataProtection () / / windows, Linux, macOS can be saved to the file system .PersistKeysToFileSystem (new System.IO.DirectoryInfo ("C:\\ share_keys\\") / windows can be saved to the registry .PersistKeysToRegistry (Microsoft.Win32.RegistryKey.FromHandle (null))}
You can also extend your own methods to define your own storage, such as using a database or Redis.
However, in general, if deployed on linux, it needs to be extended. Let's take a look at what we should do if we want to use redis storage.
How do I extend the storage location of the encryption key collection?
First, define a redis implementation class RedisXmlRepository.cs for the IXmlRepository interface:
Public class RedisXmlRepository: IXmlRepository, IDisposable {public static readonly string RedisHashKey = "DataProtectionXmlRepository"; private IConnectionMultiplexer _ connection; private bool _ disposed = false; public RedisXmlRepository (string connectionString, ILogger logger): this (ConnectionMultiplexer.Connect (connectionString), logger) {} public RedisXmlRepository (IConnectionMultiplexer connection, ILogger 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\ configuration =\ s * [^,] *", "password=****", RegexOptions.IgnoreCase); this.Logger.LogDebug ("Storing data protection keys in Redis: {RedisConfiguration}", configuration);} public ILogger Logger {get; private set;} public void Dispose () {this.Dispose (true);} public IReadOnlyCollection GetAllElements () {var database = this._connection.GetDatabase () Var hash = database.HashGetAll (RedisHashKey); var elements = new List (); 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;}
Then define an extension method in any extension class:
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)) } / / because IXmlRepository has been injected into services.AddDataProtection (), it should be removed first / / it should be encapsulated as a method to call. For readers to understand, I directly wrote for (int I = builder.Services.Count-1; I > = 0; Imura -) {if (builder.Services [I]? .ServiceType = = descriptor.ServiceType) {builder.Services.RemoveAt (I) }} var descriptor = ServiceDescriptor.Singleton (services = > new RedisXmlRepository (redisConnectionString, services.GetRequiredService ()) builder.Services.Add (descriptor); return builder.Use ();}
In the end, the Services about DataProtection goes like this:
Public void ConfigureServices (IServiceCollection services) {services.AddDataProtection () / = the following is the unique ID = / / sets the unique ID of the application .SetApplicationName ("my_app_sample_identity") / / the following is the main encryption key = / / windows dpaip as the primary encryption key .ProtectKeysWithDpapi () / if it is windows 8 + or windows server2012+ can use this option (based on Windows DPAPI-NG) .ProtectKeysWithDpapiNG ("SID= {current account SID}", DpapiNGProtectionDescriptorFlags.None) / / if it is windows 8 + or windows server2012+ can use this option (based on certificate) .ProtectKeysWithDpapiNG ("CERTIFICATE=HashId:3BCE558E2AD3E0E34A7743EAB5AEA2A9BD2575A0", DpapiNGProtectionDescriptorFlags.None) / use certificate as primary encryption key Currently, it is only supported by widnows, but not by linux. .ProtectKeysWithCertificate (); / / = the following is the storage location = / / windows, Linux, macOS can be saved to the file system in this way. PersistKeysToFileSystem (new System.IO.DirectoryInfo ("C:\\ share_keys\\")) / / windows can be saved to the registry in this way. PersistKeysToRegistry (Microsoft.Win32.RegistryKey.FromHandle (null)) / / to redis .PersistKeysToRedis (Configuration.Section ["RedisConnection"])}
In the above configuration, I have listed all the configurations that can be used, which should be selected according to the actual situation in the actual project.
The above is how to configure ASP.NETCore data protection DataProtection cluster scenarios. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.