BTW.KeycloakJwtGenerator.NetCore31 1.0.1

dotnet add package BTW.KeycloakJwtGenerator.NetCore31 --version 1.0.1
                    
NuGet\Install-Package BTW.KeycloakJwtGenerator.NetCore31 -Version 1.0.1
                    
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="BTW.KeycloakJwtGenerator.NetCore31" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BTW.KeycloakJwtGenerator.NetCore31" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="BTW.KeycloakJwtGenerator.NetCore31" />
                    
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 BTW.KeycloakJwtGenerator.NetCore31 --version 1.0.1
                    
#r "nuget: BTW.KeycloakJwtGenerator.NetCore31, 1.0.1"
                    
#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 BTW.KeycloakJwtGenerator.NetCore31@1.0.1
                    
#: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=BTW.KeycloakJwtGenerator.NetCore31&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=BTW.KeycloakJwtGenerator.NetCore31&version=1.0.1
                    
Install as a Cake Tool

BTW.KeycloakJwtGenerator.NetCore31

NuGet License .NET Core

Variante netcoreapp3.1 de BTW.KeycloakJwtGenerator. Genera JWTs centralizados usando Keycloak como Identity Provider para sistemas ASP.NET Core 3.1 legacy.

Para .NET 6 / 7 / 8 / 10 usa el paquete principal BTW.KeycloakJwtGenerator.
Para .NET Framework 4.6.1 (Web API 2 + OWIN) usa BTW.KeycloakJwtGenerator.NetFramework461.


¿Para qué sirve?

Tu Sistema ASP.NET Core 3.1 (auth propia) → BTW.KeycloakJwtGenerator → Keycloak → JWT con tus claims
  • ✅ Tu sistema mantiene su autenticación (BD, LDAP, Active Directory)
  • ✅ Keycloak firma y emite el JWT
  • ✅ Claims personalizados que tú defines
  • ✅ Cualquier API que apunte al mismo realm valida el token

Instalación

dotnet add package BTW.KeycloakJwtGenerator.NetCore31

Configuración en appsettings.json

{
  "KeycloakJwt": {
    "BaseUrl": "http://localhost:8080",
    "Realm": "mi-realm",
    "ClientId": "mi-sistema",
    "ClientSecret": "mi-secret",
    "SystemName": "Sistema A"
  }
}

Registro en Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Generar JWT
        services.AddKeycloakJwtGenerator(Configuration);

        // Validar JWT (para APIs que solo consumen tokens)
        services.AddKeycloakJwtValidation(Configuration);

        // O ambos en una sola llamada
        // services.AddKeycloakJwtFull(Configuration);

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
        app.UseAuthentication();   // debe ir antes de UseAuthorization
        app.UseAuthorization();
        app.UseEndpoints(endpoints => endpoints.MapControllers());
    }
}

Uso — Controlador de login

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IMyAuthService _myAuth;
    private readonly IKeycloakJwtGenerator _jwt;

    public AuthController(IMyAuthService myAuth, IKeycloakJwtGenerator jwt)
    {
        _myAuth = myAuth;
        _jwt    = jwt;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginRequest req)
    {
        // 1. Tu autenticación propia (BD, LDAP, etc.)
        var user = await _myAuth.ValidateAsync(req.Username, req.Password);
        if (user == null) return Unauthorized();

        // 2. Claims que decides poner en el JWT
        var claims = new Dictionary<string, object>
        {
            ["departamento"] = user.Departamento,
            ["nivel_acceso"] = user.NivelAcceso,
            ["permisos"]     = user.Permisos   // string[]
        };

        // 3. Generar JWT via Keycloak
        var token = await _jwt.GenerateTokenAsync(req.Username, claims);

        return Ok(token);
    }

    [HttpPost("refresh")]
    public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
    {
        try
        {
            var token = await _jwt.RefreshTokenAsync(req.RefreshToken);
            return Ok(token);
        }
        catch (KeycloakAuthenticationException)
        {
            return Unauthorized();
        }
    }

    [HttpPost("logout")]
    [Authorize]
    public async Task<IActionResult> Logout([FromBody] LogoutRequest req)
    {
        await _jwt.RevokeTokenAsync(req.RefreshToken);
        return NoContent();
    }
}

Uso — Controlador protegido

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class RecursoController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var departamento = User.FindFirst("departamento")?.Value;
        var nivelAcceso  = User.FindFirst("nivel_acceso")?.Value;
        return Ok(new { departamento, nivelAcceso });
    }
}

API completa

Método Descripción
GenerateTokenAsync(username, claims) Genera JWT: admin token → sync user → Token Exchange
GenerateTokenAsync(GenerateTokenRequest) Igual, con email/nombre/roles opcionales
RefreshTokenAsync(refreshToken) Renueva access + refresh token
ValidateTokenAsync(token) Introspección remota en Keycloak
RevokeTokenAsync(refreshToken) Logout en Keycloak

Opciones de configuración

Opción Descripción Default
BaseUrl URL base de Keycloak http://localhost:8080
Realm Nombre del Realm master
ClientId Client ID del service account
ClientSecret Client Secret
SystemName Nombre del sistema (claim sistema_origen) null
TimeoutSeconds Timeout HTTP 30
EnableAdminTokenCache Cachear el admin token true
AdminTokenCacheMinutes Tiempo de caché del admin token 4
UseTokenExchange Usar Token Exchange (fallback a service account) true
MaxRetries Reintentos en fallo 3

Excepciones

Excepción Cuándo se lanza
KeycloakAuthenticationException Credenciales del service account inválidas
KeycloakConnectionException No se puede conectar con Keycloak (503)
KeycloakUserSyncException Error al crear/actualizar el usuario en el realm
KeycloakConfigurationException Opciones inválidas (BaseUrl, Realm, ClientId, ClientSecret vacíos)
TokenExchangeException Token Exchange fallido (capturada internamente, fallback automático)

Configuración mínima de Keycloak

  1. Crear un Client con Client authentication: ON y Service accounts roles: ✅
  2. Asignar roles al service account: manage-users, view-users, impersonation
  3. Protocol Mappers por cada claim custom: tipo User Attribute, Add to access token: ✅
  4. (Opcional) Habilitar Token Exchange: KC_FEATURES=token-exchange en Keycloak

Licencia

MIT — ver licencia


Desarrollado por By The Wave (BTW)

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
.NET Core netcoreapp3.1 is compatible. 
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
1.0.1 100 4/28/2026
1.0.0 94 4/28/2026