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
<PackageReference Include="SimpleW.Helper.Jwt" Version="26.0.0" />
<PackageVersion Include="SimpleW.Helper.Jwt" Version="26.0.0" />
<PackageReference Include="SimpleW.Helper.Jwt" />
paket add SimpleW.Helper.Jwt --version 26.0.0
#r "nuget: SimpleW.Helper.Jwt, 26.0.0"
#:package SimpleW.Helper.Jwt@26.0.0
#addin nuget:?package=SimpleW.Helper.Jwt&version=26.0.0
#tool nuget:?package=SimpleW.Helper.Jwt&version=26.0.0
SimpleW.Helper.Jwt
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 | Versions 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. |
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.
