Common.JwtHelper 1.0.0

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

Common.JwtHelper

A lightweight, generic JWT helper package for ASP.NET Core 10 that provides easy access to JWT tokens and claims with full generic claim support.

NuGet Version NuGet Downloads License: MIT .NET

Features

  • ✅ Generic claim access - Retrieve any claim by type name
  • ✅ Type conversion - Automatic conversion of claim values to specific types
  • ✅ Multiple claims support - Handle multiple claims of the same type
  • ✅ Null-safe - Built-in null checking and safe defaults
  • ✅ ASP.NET Core 10 compatible - Optimized for the latest .NET version
  • ✅ Lightweight - Minimal dependencies, focused functionality
  • ✅ Flexible - Works with any JWT structure and claim naming convention
  • ✅ Production-ready - Proper error handling and comprehensive testing

Installation

Package Manager

Install-Package Common.JwtHelper

.NET CLI

dotnet add package Common.JwtHelper

PackageReference

<PackageReference Include="Common.JwtHelper" Version="1.0.0" />

Minimal Setup Example

var builder = WebApplication.CreateBuilder(args);

// Required for Common.JwtHelper
builder.Services.AddHttpContextAccessor();
builder.Services.Add.JwtHelper();

var app = builder.Build();

// Your middleware and endpoints...
app.Run();

Quick Start

1. Register Services

In your Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add JWT authentication (configure per your setup)
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });
//Add AddHttpContextAccessor 
builder.Services.AddHttpContextAccessor() // required for JWT Helper
// Add Common.JwtHelper services
builder.Services.Add.JwtHelper();

var app = builder.Build();

2. Use in Controllers

[ApiController]
[Route("api/[controller]")]
[Authorize] // Ensure user is authenticated
public class UserController : ControllerBase
{
    private readonly IJwtContext _jwtContext;

    public UserController(IJwtContext jwtContext)
    {
        _jwtContext = jwtContext;
    }

    [HttpGet("profile")]
    public IActionResult GetProfile()
    {
        var token = _jwtContext.Token;
        var userId = _jwtContext.GetClaimValue("userId");
        var email = _jwtContext.GetClaimValue(ClaimTypes.Email);
        var userIdGuid = _jwtContext.GetClaimValue<Guid>("userId");
        var roles = _jwtContext.GetClaims(ClaimTypes.Role);
        var hasAdminRole = _jwtContext.HasClaim(ClaimTypes.Role, "Admin");

        return Ok(new
        {
            UserId = userId,
            Email = email,
            Roles = roles,
            HasAdminRole = hasAdminRole,
            TokenPreview = token?.Substring(0, Math.Min(20, token?.Length ?? 0)) + "..."
        });
    }
}

3. Use in Services

public class UserService
{
    private readonly IJwtContext _jwtContext;
    private readonly ILogger<UserService> _logger;

    public UserService(IJwtContext jwtContext, ILogger<UserService> logger)
    {
        _jwtContext = jwtContext;
        _logger = logger;
    }

    public void ProcessUserData()
    {
        var userId = _jwtContext.GetClaimValue<Guid?>("userId");

        if (userId == null)
        {
            _logger.LogWarning("User ID claim not found in token");
            return;
        }

        _logger.LogInformation("Processing data for user {UserId}", userId);
    }
}

Advanced Usage

Custom Claim Types
public static class CustomClaimTypes
{
    public const string EmployeeId = "employee_id";
    public const string Department = "department";
    public const string Permissions = "permissions";
    public const string TenantId = "tenant_id";
}

// Usage:
var employeeId = _jwtContext.GetClaimValue(CustomClaimTypes.EmployeeId);
var department = _jwtContext.GetClaimValue(CustomClaimTypes.Department);
var permissions = _jwtContext.GetClaims(CustomClaimTypes.Permissions);

Middleware Integration

public class UserInfoMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<UserInfoMiddleware> _logger;

    public UserInfoMiddleware(RequestDelegate next, ILogger<UserInfoMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context, IJwtContext jwtContext)
    {
        var userId = jwtContext.GetClaimValue("userId");
        var userAgent = context.Request.Headers.UserAgent.ToString();

        _logger.LogInformation("Request from UserId: {UserId}, UserAgent: {UserAgent}",
            userId ?? "Anonymous", userAgent);

        await _next(context);
    }
}

// Register middleware
app.UseMiddleware<UserInfoMiddleware>();

Troubleshooting

Common Issues

1. IJwtContext returns null values
  • Ensure [Authorize] attribute is applied to your controller/action
  • Verify JWT token is properly formatted in the Authorization header
  • Check that claims exist in the token
2. Dependency Injection errors
  • Make sure AddHttpContextAccessor() is called before Add.JwtHelper()
  • Verify services are registered in the correct order in Program.cs
3. Claim not found
  • Check claim type spelling (case-sensitive)
  • Verify the claim exists in your JWT token payload
Built with ❤️ for the .NET community by Muammar Siddiqui
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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 162 2/9/2026