JG.AuthKit 1.0.0

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

dotnet-auth-kit

NuGet Downloads License CI


JWT authentication and authorization library for .NET APIs. Handles token issuing, refresh token rotation with reuse detection, role and claim-based access control, token blacklisting, key rotation, and ASP.NET Core middleware integration -- with secure defaults and minimal configuration.

Features

  • JWT Issuing -- Generate signed access tokens with configurable expiry, audience, issuer, and custom claims. Supports HS256/384/512, RS256/384/512, and ES256/384/512 algorithms.
  • Refresh Token Rotation -- Single-use refresh tokens with automatic rotation. Reuse of a consumed token triggers family-wide revocation to mitigate token theft.
  • Role-Based Access Control -- Define roles in token requests and enforce them via [Authorize(Roles = "admin")] or custom RoleRequirement policies.
  • Claim-Based Access Control -- Fine-grained authorization using custom claims with ClaimRequirement and built-in authorization handlers.
  • Token Blacklisting -- Revoke individual access tokens before expiry. In-memory store included; bring your own Redis or database implementation.
  • Key Rotation -- Support multiple signing keys with time-based activation windows. Old keys remain valid for verification while new keys are used for signing.
  • Claim Transformation -- Plug in IClaimTransformer implementations to enrich claims during token issuance (e.g., load roles from a database).
  • Middleware Integration -- Authentication handler that plugs into ASP.NET Core's UseAuthentication() / UseAuthorization() pipeline. Single registration with services.AddAuthKit().
  • Background Cleanup -- Automatic expiry of blacklisted and consumed refresh tokens via a configurable background service.
  • Extensible Storage -- Default in-memory stores for both token blacklist and refresh tokens. Replace with your own ITokenBlacklistStore and IRefreshTokenStore implementations for distributed deployments.

Installation

dotnet add package JG.AuthKit

Requires .NET 8.0 or later.

Quick Start

1. Register Services

builder.Services.AddAuthKit(options =>
{
    options.Secret = builder.Configuration["Jwt:Secret"];
    options.Issuer = "my-api";
    options.Audience = "my-app";
    options.AccessTokenExpiry = TimeSpan.FromMinutes(15);
    options.RefreshTokenExpiry = TimeSpan.FromDays(30);
});

2. Add Middleware

var app = builder.Build();
app.UseAuthKit();
app.MapControllers();
app.Run();

3. Issue Tokens

app.MapPost("/auth/login", async (LoginRequest login, ITokenService tokenService) =>
{
    // Validate credentials against your user store
    var user = await userService.ValidateAsync(login.Email, login.Password);
    if (user is null)
        return Results.Unauthorized();

    var result = await tokenService.IssueTokenAsync(new TokenRequest
    {
        Subject = user.Id,
        Roles = user.Roles.ToList(),
        Claims = [new Claim("tenant", user.TenantId)],
    });

    return Results.Ok(new
    {
        result.AccessToken,
        result.RefreshToken,
        result.ExpiresAt,
    });
});

4. Refresh Tokens

app.MapPost("/auth/refresh", async (RefreshBody body, IRefreshTokenService refreshService) =>
{
    try
    {
        var result = await refreshService.RefreshAsync(new RefreshRequest
        {
            RefreshToken = body.RefreshToken,
        });
        return Results.Ok(new { result.AccessToken, result.RefreshToken, result.ExpiresAt });
    }
    catch (InvalidOperationException ex)
    {
        return Results.Problem(ex.Message, statusCode: 401);
    }
});

5. Protect Endpoints

// Require authentication
app.MapGet("/me", [Authorize] (ClaimsPrincipal user) =>
{
    var sub = user.FindFirst("sub")?.Value;
    return Results.Ok(new { UserId = sub });
});

// Require specific role
app.MapGet("/admin", [Authorize(Roles = "admin")] () => Results.Ok("Admin area"));

6. Revoke Tokens

app.MapPost("/auth/logout", async (LogoutBody body, ITokenService tokenService,
    IRefreshTokenService refreshService) =>
{
    // Blacklist the access token
    await tokenService.RevokeTokenAsync(body.AccessToken);

    // Revoke the refresh token family
    if (body.RefreshToken is not null)
        await refreshService.RevokeAsync(body.RefreshToken);

    return Results.Ok();
});

Key Rotation

Support multiple signing keys with time-based activation for zero-downtime key rotation:

builder.Services.AddAuthKit(options =>
{
    options.Issuer = "my-api";

    // Old key: still valid for verification, no longer signs new tokens
    options.SigningKeys.Add(new SigningKeyDescriptor
    {
        KeyId = "key-2025-06",
        Key = new SymmetricSecurityKey(Convert.FromBase64String(oldKey)),
        Algorithm = "HS256",
        ActiveFrom = new DateTimeOffset(2025, 6, 1, 0, 0, 0, TimeSpan.Zero),
        ActiveUntil = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero),
    });

    // Current key: used for signing
    options.SigningKeys.Add(new SigningKeyDescriptor
    {
        KeyId = "key-2026-01",
        Key = new SymmetricSecurityKey(Convert.FromBase64String(currentKey)),
        Algorithm = "HS256",
        ActiveFrom = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero),
    });
});

Custom Stores

The default in-memory stores work for single-instance deployments. For distributed setups, register your own implementations before calling AddAuthKit:

// Register before AddAuthKit -- these won't be overwritten
builder.Services.AddSingleton<ITokenBlacklistStore, RedisTokenBlacklistStore>();
builder.Services.AddSingleton<IRefreshTokenStore, PostgresRefreshTokenStore>();

builder.Services.AddAuthKit(options => { ... });

Claim Transformation

Enrich claims at token issuance time:

public class RoleEnricher : IClaimTransformer
{
    private readonly IRoleRepository _roles;
    public RoleEnricher(IRoleRepository roles) => _roles = roles;

    public async ValueTask<IReadOnlyList<Claim>> TransformAsync(
        IReadOnlyList<Claim> claims, CancellationToken cancellationToken)
    {
        var sub = claims.FirstOrDefault(c => c.Type == "sub")?.Value;
        if (sub is null) return claims;

        var roles = await _roles.GetRolesAsync(sub, cancellationToken);
        var enriched = new List<Claim>(claims);
        foreach (var role in roles)
            enriched.Add(new Claim(ClaimTypes.Role, role));
        return enriched;
    }
}

// Register:
builder.Services.AddSingleton<IClaimTransformer, RoleEnricher>();

Policy-Based Authorization

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOrEditor", policy =>
        policy.AddRequirements(new RoleRequirement("admin", "editor")));

    options.AddPolicy("HasTenant", policy =>
        policy.AddRequirements(new ClaimRequirement("tenant")));

    options.AddPolicy("Engineering", policy =>
        policy.AddRequirements(new ClaimRequirement("department", "engineering", "devops")));
});

Configuration Reference

Option Default Description
Secret -- HMAC signing key (min 32 bytes UTF-8)
SigningKey -- SecurityKey for RSA/ECDSA signing
SigningAlgorithm "HS256" Signing algorithm
Issuer -- Token issuer (iss claim)
Audience -- Token audience (aud claim)
AccessTokenExpiry 15 min Access token lifetime
RefreshTokenExpiry 30 days Refresh token lifetime
ClockSkew 1 min Validation clock skew tolerance
EnableRefreshTokenRotation true Enable refresh token rotation
EnableTokenBlacklist true Enable token revocation
CleanupInterval 5 min Background cleanup interval

Documentation

  • API Reference -- Detailed API docs with examples for every feature

Contributing

Contributions are welcome. Please feel free to submit a Pull Request.

Benchmarks

Run performance benchmarks with BenchmarkDotNet:

# List all available benchmarks
dotnet run --project tests/dotnet-auth-kit.Benchmarks -c Release -- --list flat

# Run all benchmarks
dotnet run --project tests/dotnet-auth-kit.Benchmarks -c Release -- --filter *

# Run token service benchmarks only
dotnet run --project tests/dotnet-auth-kit.Benchmarks -c Release -- --filter *TokenService*

License

Licensed under the Apache License 2.0. See LICENSE for details.

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
1.0.0 89 2/25/2026