SimpleW.Helper.Jwt 26.0.0

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

SimpleW.Helper.Jwt

website

NuGet Package NuGet Downloads License <br/> Linux MacOS Windows (Visual Studio)

Features

This package provides lightweight JWT Bearer helpers for SimpleW. It allows you to create and validate JWT tokens using HttpIdentity or HttpPrincipal, with full support for roles and custom properties. Supports HS256, HS384, and HS512 algorithms, with optional issuer and audience validation.

Getting Started

The minimal API

using System;
using System.Net;
using SimpleW;
using SimpleW.Helper.Jwt;

namespace Sample {
    class Program {

        static async Task Main() {

            var helper = new JwtBearerHelper(options => {
                options.SecretKey = "super-secret-key";
                options.Issuer = "simplew";
                options.Audience = "api";
            });

            var identity = new HttpIdentity(
                isAuthenticated: true,
                authenticationType: "Custom",
                identifier: "user-123",
                name: "John Doe",
                email: "john@doe.com",
                roles: new[] { "admin" },
                properties: null
            );

            string token = helper.CreateToken(
                identity,
                lifetime: TimeSpan.FromHours(1)
            );

            if (helper.TryValidateToken(token, out var principal, out var error)) {
                Console.WriteLine($"User: {principal.Identity.Name}");
            }
            else {
                Console.WriteLine($"Invalid token: {error}");
            }

        }
    }

}

Middleware Integration

You can restore session.Principal from the Authorization header in a middleware.

using System;
using System.Collections.Generic;
using SimpleW;
using SimpleW.Helper.Jwt;

JwtBearerHelper helper = new(options => {
    options.SecretKey = "super-secret-key";
    options.Issuer = "simplew";
    options.Audience = "api";
});

server.UseMiddleware(async (session, next) => {
    if (helper.TryAuthenticate(session, out HttpPrincipal principal)) {
        session.Principal = principal;
    }

    await next();
});

Custom Attributes In Middleware

Because SimpleW exposes route metadata through session.Metadata, you can combine core auth metadata with custom JWT attributes in one middleware.

using SimpleW;
using SimpleW.Helper.Jwt;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class JwtAuthAttribute : Attribute, IHandlerMetadata {
}

JwtBearerHelper helper = new(options => {
    options.SecretKey = "super-secret-key";
    options.Issuer = "simplew";
    options.Audience = "api";
});

server.UseMiddleware(async (session, next) => {
    if (helper.TryAuthenticate(session, out HttpPrincipal principal)) {
        session.Principal = principal;
    }

    if (session.Metadata.Has<AllowAnonymousAttribute>()) {
        await next();
        return;
    }

    JwtAuthAttribute? auth = session.Metadata.Get<JwtAuthAttribute>();
    RequireRoleAttribute? requiredRole = session.Metadata.Get<RequireRoleAttribute>();

    if (auth == null && requiredRole == null) {
        await next();
        return;
    }

    if (!session.Principal.IsAuthenticated) {
        await session.Response.Unauthorized().SendAsync();
        return;
    }

    if (requiredRole != null && !session.Principal.IsInRoles(requiredRole.Role)) {
        await session.Response
                     .Status(403)
                     .Json(new { ok = false, error = "forbidden", role = requiredRole.Role })
                     .SendAsync();
        return;
    }

    await next();
});

[JwtAuth]
[Route("/api/account")]
public class AccountController : Controller {

    [AllowAnonymous]
    [Route("GET", "/public")]
    public object Public() {
        return new { ok = true };
    }

    [Route("GET", "/me")]
    public object Me() {
        return new {
            id = Principal.Identity.Identifier,
            name = Principal.Name,
            roles = Principal.Roles
        };
    }

    [RequireRole("admin")]
    [Route("GET", "/admin")]
    public object Admin() {
        return new { ok = true, area = "admin" };
    }
}

If you want a ready-to-use module that restores the principal automatically and protects handlers with metadata for you, use SimpleW.Service.Jwt.

Documentation

To check out docs, visit simplew.net.

Changelog

Detailed changes for each release are documented in the CHANGELOG.

Contribution

Feel free to report issue.

License

This library is under the MIT License.

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 is compatible.  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 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.
  • net10.0

  • net8.0

  • net9.0

NuGet packages (1)

Showing the top 1 NuGet packages that depend on SimpleW.Helper.Jwt:

Package Downloads
SimpleW.Service.Jwt

JWT Bearer convenience module for SimpleW with automatic principal restoration and metadata-driven auth and role enforcement built on top of SimpleW.Helper.Jwt.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
26.0.0 109 4/26/2026
Loading failed