Security, Json Web Token, Password Service, Encrypt, Decrypt, Seguridad, Token de sesión, Servicio de contraseña, encriptador, desencriptador
-
Visual Studio >= 2019
-
NET TargetFramework >= net7.0
-
Net Core SDK >= 7.0.100
-
C# >= 11.0
-
Conocimientos sobre Inyección de Dependencias
Se puede instalar usando el administrador de paquetes Nuget o CLI dotnet.
Nuget
Install-Package Kitpymes.Core.Security
CLI dotnet
dotnet add package Kitpymes.Core.Security
public class SecuritySettings
{
public EncryptorSettings EncryptorSettings { get; set; } = new EncryptorSettings();
public JsonWebTokenSettings JsonWebTokenSettings { get; set; } = new JsonWebTokenSettings();
public PasswordSettings PasswordSettings { get; set; } = new PasswordSettings();
}
public class SecurityOptions
{
public SecurityOptions WithEncryptor(IConfiguration configuration) {}
public SecurityOptions WithEncryptor(Action<EncryptorOptions> options) {}
public SecurityOptions WithEncryptor(EncryptorSettings settings) {}
public SecurityOptions WithJsonWebToken(IConfiguration configuration) {}
public SecurityOptions WithJsonWebToken(Action<JsonWebTokenOptions> option) {}
public SecurityOptions WithJsonWebToken(JsonWebTokenSettings settings) {}
public SecurityOptions WithPassword(IConfiguration configuration) {}
public SecurityOptions WithPassword(Action<PasswordOptions> option) {}
public SecurityOptions WithPassword(PasswordSettings settings) {}
}
public static class SecurityServiceCollectionExtensions
{
public static IServiceCollection LoadSecurity(this IServiceCollection services, IConfiguration configuration) {}
public static IServiceCollection LoadSecurity(this IServiceCollection services, Action<SecurityOptions> options) {}
public static IServiceCollection LoadSecurity(this IServiceCollection services, SecuritySettings settings) {}
}
public class EncryptorSettings
{
public bool? Enabled { get; set; }
public string? ApplicationName { get; set; }
public int? KeyLifetimeFromDays { get; set; }
public string? PersistKeysToFileSystem { get; set; }
}
public class EncryptorOptions
{
public EncryptorOptions WithEnabled(bool enabled = true) {}
public EncryptorOptions WithApplicationName(string? applicationName) {}
public EncryptorOptions WithKeyLifetimeFromDays(int? keyLifetimeFromDays) {}
public EncryptorOptions WithPersistKeysToFileSystems(string? persistKeysToFileSystem) {}
}
public static class EncryptorServiceCollectionExtensions
{
public static IEncryptorService GetEncryptor(this IServiceCollection services) {}
public static IServiceCollection LoadEncryptor(this IServiceCollection services, Action<EncryptorOptions> settings) {}
public static IServiceCollection LoadEncryptor(this IServiceCollection services, EncryptorSettings settings) {}
public static IServiceCollection LoadEncryptor(this IServiceCollection services, Action<IDataProtectionBuilder> dataProtectionBuilder) {}
}
public interface IEncryptorService
{
string Encrypt(string? value, TimeSpan? lifetime = null);
string Decrypt(string? value);
string Encrypt<T>(T value, TimeSpan? lifetime = null) where T : class;
T Decrypt<T>(string? value) where T : class, new();
}
public interface IJsonWebTokenService
{
(string Token, string Expire) Encode(IList<Claim> claims, Dictionary<string, object>? headers = null);
Dictionary<string, object> Decode(string? token);
Task<(string Token, string Expire)> EncodeAsync(IList<Claim> claims, Dictionary<string, object>? headers = null);
Task<Dictionary<string, object>> DecodeAsync(string? token);
}
public class ExpireSettings
{
public int? Days { get; set; }
public int? Hours { get; set; }
public int? Minutes { get; set; }
public int? Seconds { get; set; }
}
public class JsonWebTokenSettings
{
[JsonIgnore]
public TokenValidationParameters TokenValidationParameters => new TokenValidationParameters
{
ValidateIssuerSigningKey = !string.IsNullOrWhiteSpace(Key),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key)),
ValidateIssuer = !string.IsNullOrWhiteSpace(ValidIssuer),
ValidIssuer = ValidIssuer,
ValidateAudience = !string.IsNullOrWhiteSpace(ValidAudience),
ValidAudience = ValidAudience,
ValidateLifetime = !(LifetimeValidator is null),
LifetimeValidator = LifetimeValidator,
// Tiempo de caducidad del búfer, el tiempo efectivo total es igual al tiempo más el tiempo de caducidad de Jwt. Si no está configurado, el valor predeterminado es 5 minutos.
ClockSkew = TimeSpan.FromSeconds(30),
RequireExpirationTime = _requireExpirationTime,
};
[JsonIgnore]
public LifetimeValidator LifetimeValidator { get; set; } = (before, expires, token, param) => expires > DateTime.UtcNow;
public ExpireSettings Expire { get; set; } = new ExpireSettings();
public bool? Enabled { get; set; }
public string? ValidAudience { get; set; }
public string? ValidIssuer { get; set; }
public string? Key { get; set; }
public string? AuthenticateScheme { get; set; }
public string? ChallengeScheme { get; set; }
public bool? RequireExpirationTime { get; set; }
}
public static class JsonWebTokenServiceCollectionExtensions
{
public static IJsonWebTokenService GetJsonWebToken(this IServiceCollection services) {}
public static IServiceCollection LoadJsonWebToken(this IServiceCollection services, Action<JsonWebTokenOptions>? options = null, bool enabled = true) {}
public static IServiceCollection LoadJsonWebToken(this IServiceCollection services, JsonWebTokenSettings settings) {}
}
public interface IPasswordService
{
string? CreateRandom();
(bool hasErrors, string? hashPassword, List<PasswordResult>? errors) Create(string? plainPassword);
bool Verify(string? plainPassword, string hashPassword);
(bool hasErrors, List<PasswordResult>? errors) Validate(string? plainPassword);
}
public enum PasswordResult
{
RequiredValue,
RequireDigit,
RequiredMinLength,
RequiredUniqueChars,
RequireEspecialChars,
RequireLowercase,
RequireUppercase,
}
public class PasswordSettings
{
public bool? Enabled { get; set; }
public bool? RequireDigit { get; set; }
public bool? RequireLowercase { get; set; }
public bool? RequireUppercase { get; set; }
public bool? RequireEspecialChars { get; set; }
public bool? RequiredUniqueChars { get; set; }
public int? RequiredMinLength { get; set; }
}
public static class PasswordServiceCollectionExtensions
{
public static IPasswordService GetPassword(this IServiceCollection services) {}
public static IServiceCollection LoadPassword(this IServiceCollection services, Action<PasswordOptions>? options = null, bool enabled = true) {}
public static IServiceCollection LoadPassword(this IServiceCollection services, PasswordSettings settings) {}
}
Cada proyecto tiene su respectivo test, se ejecutan desde el "Explorador de pruebas"
- NET Core - Framework de trabajo
- C# - Lenguaje de programación
- Inserción de dependencias - Patrón de diseño de software
- MSTest - Pruebas unitarias
- Nuget - Manejador de dependencias
- Visual Studio - Entorno de programacion
- Sebastian R Ferrari - Trabajo Inicial - kitpymes
- Este proyecto está bajo la Licencia LICENSE
- Este proyecto fue diseñado para compartir, creemos que es la mejor forma de ayudar 📢
- Cada persona que contribuya sera invitada a tomar una 🍺
- Gracias a todos! 🤓
Kitpymes 😊