EV.ShieldAuth 8.0.0

dotnet add package EV.ShieldAuth --version 8.0.0
                    
NuGet\Install-Package EV.ShieldAuth -Version 8.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="EV.ShieldAuth" Version="8.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EV.ShieldAuth" Version="8.0.0" />
                    
Directory.Packages.props
<PackageReference Include="EV.ShieldAuth" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add EV.ShieldAuth --version 8.0.0
                    
#r "nuget: EV.ShieldAuth, 8.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package EV.ShieldAuth@8.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=EV.ShieldAuth&version=8.0.0
                    
Install as a Cake Addin
#tool nuget:?package=EV.ShieldAuth&version=8.0.0
                    
Install as a Cake Tool

🛡️ EV.ShieldAuth

Una librería robusta y fácil de usar para autenticación JWE/JWT en aplicaciones ASP.NET Core.

✨ Características

  • 🔒 Generación de Tokens JWE - Crea tokens encriptados para mayor seguridad (Payload no visible)
  • 🔐 Generación de Tokens JWT - Crea tokens estándar JSON Web Tokens
  • Validación de Tokens - Valida y extrae claims de los tokens
  • 🎯 Autorización Basada en Roles - Soporte integrado para políticas basadas en roles
  • 📝 Logging Completo - Logging integrado para debugging y monitoreo
  • Soporte Async/Await - API completamente asíncrona
  • 🔧 Configurable - Opciones de configuración flexibles

📦 Instalación

dotnet add package EV.ShieldAuth

O vía NuGet Package Manager:

Install-Package EV.ShieldAuth

🚀 Inicio Rápido

1. Configurar en appsettings.json

{
  "ShieldAuth": {
    "ClientId": "tu-client-id",
    "EncryptionKey": "tu-clave-encriptacion-base64",
    "SigningKey": "tu-clave-firma-base64",
    "ExpireMinutes": 60,
    "Issuer": "https://tu-dominio.com",
    "Audience": "https://tu-api.com",
    "ValidateIssuerSigningKey": true,
    "ValidateIssuer": true,
    "ValidateAudience": true,
    "RequireExpirationTime": true,
    "ValidateLifetime": true,
    "RefreshTokenLifetime": 10080
  }
}

2. Registrar Servicios en Program.cs

using EV.ShieldAuth;
using EV.ShieldAuth.Options;

var builder = WebApplication.CreateBuilder(args);

// Vincular configuración
var shieldAuthConfig = new ShieldAuthConfiguration();
builder.Configuration.GetSection("ShieldAuth").Bind(shieldAuthConfig);

// Agregar servicios de ShieldAuth
builder.Services.AddShieldAuthService(shieldAuthConfig);

// Opcional: Agregar políticas basadas en roles
var roles = new List<string> { "Admin", "User", "Manager" };
builder.Services.AddShieldAuthPolicyService(roles);

var app = builder.Build();

// Habilitar autenticación y autorización
app.UseAuthentication();
app.UseAuthorization();

app.Run();

3. Generar Tokens

using EV.ShieldAuth.Interfaces;
using System.Security.Claims;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IShieldAuthService _shieldAuthService;

    public AuthController(IShieldAuthService shieldAuthService)
    {
        _shieldAuthService = shieldAuthService;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest request)
    {
        // Validar credenciales (tu lógica aquí)
        
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, "elkin.vasquez"),
            new Claim(ClaimTypes.Email, "elkin.vasquez@example.com"),
            new Claim(ClaimTypes.Name, "Elkin Vasquez")
        };

        var roles = new List<string> { "User", "Admin" };

        // Generar JWE para tokens encriptados
        var result = await _shieldAuthService.GenerateTokenJwe(claims, roles);

        // Generar JWT
        //var result = await _shieldAuthService.GenerateTokenJwt(claims, roles);
                
        if (result.Succeeded)
        {
            return Ok(result);
        }

        return Unauthorized();
    }
}

4. Proteger Endpoints

[Authorize] // Requiere autenticación
[HttpGet("profile")]
public IActionResult GetProfile()
{
    var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    return Ok(new { UserId = userId });
}

[Authorize(Roles = "Admin")] // Requiere rol Admin
[HttpDelete("users/{id}")]
public IActionResult DeleteUser(string id)
{
    // Solo admins pueden acceder aquí
    return Ok();
}

[Authorize(Policy = "Manager")] // Requiere política Manager
[HttpGet("reports")]
public IActionResult GetReports()
{
    return Ok();
}

5. Validar Tokens Manualmente

[HttpGet("validate")]
public async Task<IActionResult> ValidateToken([FromHeader] string authorization)
{
    var token = authorization.Replace("Bearer ", "");
    
    var claims = await _shieldAuthService.GetClaimsFromTokenAsync(token);

    if (claims.Any())
    {
        return Ok(new 
        { 
            Valid = true,
            Claims = claims.Select(c => new { c.Type, c.Value })
        });
    }

    return Unauthorized(new { Valid = false, Message = "Token inválido" });
}

🔑 Generar Claves

Las claves deben estar codificadas en Base64. Aquí te mostramos cómo generar claves seguras:

PowerShell

# Generar clave de 256 bits (32 bytes)
$bytes = New-Object byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($bytes)
[Convert]::ToBase64String($bytes)

Código C#

using System.Security.Cryptography;

var keyBytes = new byte[32]; // 256 bits
RandomNumberGenerator.Fill(keyBytes);
var base64Key = Convert.ToBase64String(keyBytes);
Console.WriteLine(base64Key);

Herramienta Online

Usa un codificador Base64 confiable con una cadena aleatoria de 32 bytes.

🔧 Opciones de Configuración

Propiedad Tipo Descripción Por Defecto
ClientId string Identificador del cliente de la aplicación -
EncryptionKey string Clave de encriptación en Base64 (para JWE) -
SigningKey string Clave de firma en Base64 -
ExpireMinutes int Tiempo de expiración del token en minutos -
Issuer string Emisor del token (claim iss) -
Audience string Audiencia del token (claim aud) -
ValidateIssuerSigningKey bool Validar la clave de firma del emisor true
ValidateIssuer bool Validar el emisor del token true
ValidateAudience bool Validar la audiencia del token true
RequireExpirationTime bool Requerir tiempo de expiración true
ValidateLifetime bool Validar el tiempo de vida del token true
RefreshTokenLifetime int Tiempo de vida del refresh token (minutos) -

📊 Modelos de Respuesta

ShieldAuthResult

{
  "token_type": "Bearer",
  "expires_in": 3600,
  "access_token": "eyJhbGc...",
  "refresh_token": "",
  "succeeded": true
}

🛠️ Uso Avanzado

Claims Personalizados

var claims = new List<Claim>
{
    new Claim("custom_claim", "custom_value"),
    new Claim("tenant_id", "tenant-123"),
    new Claim(JwtRegisteredClaimNames.Sub, "user-id")
};

var result = await _shieldAuthService.GenerateTokenJwt(claims, roles);

Manejo de Validación de Tokens

var claims = await _shieldAuthService.GetClaimsFromTokenAsync(token);

if (!claims.Any())
{
    // Token inválido, expirado o mal formado
    return Unauthorized();
}

// Procesar claims
var userId = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;

Políticas de Autorización por Roles

ShieldAuth te permite configurar fácilmente políticas basadas en roles:

// En Program.cs - Registrar políticas automáticamente
var roles = new List<string> { "Admin", "User", "Manager", "Guest" };
builder.Services.AddShieldAuthPolicyService(roles);

Esto crea automáticamente una política para cada rol. Luego puedes usarlas en tus controladores:

// Opción 1: Usar el atributo Roles
[Authorize(Roles = "Admin")]
[HttpDelete("users/{id}")]
public IActionResult DeleteUser(string id)
{
    // Solo usuarios con rol "Admin" pueden acceder
    return Ok();
}

// Opción 2: Usar el atributo Policy (nombre de la política = nombre del rol)
[Authorize(Policy = "Manager")]
[HttpGet("reports")]
public IActionResult GetReports()
{
    // Solo usuarios con rol "Manager" pueden acceder
    return Ok();
}

// Opción 3: Múltiples roles permitidos
[Authorize(Roles = "Admin,Manager")]
[HttpPut("users/{id}")]
public IActionResult UpdateUser(string id)
{
    // Admin O Manager pueden acceder
    return Ok();
}
Políticas Personalizadas Avanzadas

Si necesitas políticas más complejas, puedes crearlas manualmente:

builder.Services.AddAuthorization(options =>
{
    // Política: Requiere múltiples roles
    options.AddPolicy("SuperAdmin", policy =>
        policy.RequireRole("Admin", "SuperUser"));

    // Política: Requiere rol Y claim específico
    options.AddPolicy("PremiumAdmin", policy =>
        policy.RequireRole("Admin")
              .RequireClaim("subscription", "premium"));

    // Política: Validación personalizada
    options.AddPolicy("AdultOnly", policy =>
        policy.RequireAssertion(context =>
        {
            var ageClaim = context.User.FindFirst("age");
            return ageClaim != null && int.Parse(ageClaim.Value) >= 18;
        }));

    // Política: Basada en claim específico
    options.AddPolicy("CanExport", policy =>
        policy.RequireClaim("can_export", "true"));
});

Usar políticas personalizadas:

[Authorize(Policy = "SuperAdmin")]
[HttpPost("critical-operation")]
public IActionResult CriticalOperation()
{
    return Ok();
}

[Authorize(Policy = "AdultOnly")]
[HttpGet("adult-content")]
public IActionResult GetAdultContent()
{
    return Ok();
}
Verificar Roles en el Código

También puedes verificar roles programáticamente:

[Authorize]
[HttpGet("dashboard")]
public IActionResult GetDashboard()
{
    var isAdmin = User.IsInRole("Admin");
    var isManager = User.IsInRole("Manager");

    if (isAdmin)
    {
        // Mostrar dashboard completo
        return Ok(new { Type = "Full", Data = GetFullDashboard() });
    }
    else if (isManager)
    {
        // Mostrar dashboard limitado
        return Ok(new { Type = "Limited", Data = GetLimitedDashboard() });
    }
    
    // Dashboard básico
    return Ok(new { Type = "Basic", Data = GetBasicDashboard() });
}
Obtener Roles del Usuario
[Authorize]
[HttpGet("my-roles")]
public IActionResult GetMyRoles()
{
    var roles = User.Claims
        .Where(c => c.Type == ClaimTypes.Role)
        .Select(c => c.Value)
        .ToList();

    return Ok(new { Roles = roles });
}

Múltiples Esquemas de Autenticación

builder.Services.AddShieldAuthService(shieldAuthConfig);

// Agregar esquemas adicionales si es necesario
builder.Services.AddAuthentication()
    .AddCookie("Cookies")
    .AddGoogle("Google", options => { ... });

📝 Logging

ShieldAuth usa ILogger<T> para logging completo:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "EV.ShieldAuth": "Debug"  // Activar logs detallados de ShieldAuth
    }
  }
}

Niveles de log utilizados:

  • Debug: Detalles de generación de tokens, pasos de validación
  • Information: Operaciones exitosas, validación de configuración
  • Warning: Expiración de tokens, advertencias de tamaño de claves
  • Error: Fallos de validación, errores de configuración

🔒 Mejores Prácticas de Seguridad

  1. Usar Claves Fuertes: Mínimo 256 bits (32 bytes)
  2. Almacenar Claves de Forma Segura: Usar Azure Key Vault, AWS Secrets Manager o similar
  3. Usar JWE para Datos Sensibles: Encripta todo el payload del token
  4. Tiempos de Expiración Cortos: 15-60 minutos para access tokens
  5. Solo HTTPS: Usar siempre HTTPS en producción
  6. Rotar Claves Regularmente: Implementar estrategia de rotación de claves
  7. Validar Todos los Claims: Habilitar todas las opciones de validación en producción

🐛 Solución de Problemas

"Invalid token signature"

  • Verifica que SigningKey coincida entre generación y validación
  • Asegúrate de que la clave esté correctamente codificada en Base64

"Token has expired"

  • Verifica sincronización de hora del sistema
  • Ajusta ExpireMinutes si es necesario
  • Considera el clock skew (por defecto: 5 minutos)

"Failed to decrypt token"

  • Verifica que EncryptionKey sea correcta (para tokens JWE)
  • Asegúrate de usar validación JWE para tokens JWE

Errores de validación de configuración

  • Verifica que todos los campos requeridos estén poblados
  • Verifica que las claves sean cadenas Base64 válidas
  • Asegúrate de que ExpireMinutes > 0

Licencia

Copyright © 2025 EV. Todos los derechos reservados.


Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.0 214 10/1/2025

Características
🔒 Generación de Tokens JWE - Crea tokens encriptados para mayor seguridad (Payload no visible)
🔐 Generación de Tokens JWT - Crea tokens estándar JSON Web Tokens
✅ Validación de Tokens - Valida y extrae claims de los tokens
🎯 Autorización Basada en Roles - Soporte integrado para políticas basadas en roles
📝 Logging Completo - Logging integrado para debugging y monitoreo
⚡ Soporte Async/Await - API completamente asíncrona
🔧 Configurable - Opciones de configuración flexibles