Identity.Jwt.Token.Manager
9.0.4
dotnet add package Identity.Jwt.Token.Manager --version 9.0.4
NuGet\Install-Package Identity.Jwt.Token.Manager -Version 9.0.4
<PackageReference Include="Identity.Jwt.Token.Manager" Version="9.0.4" />
<PackageVersion Include="Identity.Jwt.Token.Manager" Version="9.0.4" />
<PackageReference Include="Identity.Jwt.Token.Manager" />
paket add Identity.Jwt.Token.Manager --version 9.0.4
#r "nuget: Identity.Jwt.Token.Manager, 9.0.4"
#addin nuget:?package=Identity.Jwt.Token.Manager&version=9.0.4
#tool nuget:?package=Identity.Jwt.Token.Manager&version=9.0.4
Token Management System
The Token Management System is a robust and flexible .NET library for managing JWT access tokens, ID tokens, and refresh tokens using RSA (RS256) or HMAC (HS256). It simplifies the process of secure token generation, validation, and expiration handling โ ideal for building authentication and authorization systems in modern web, mobile, or API-based applications.
โจ Features
- โ Generate JWT Access Tokens with user claims.
- ๐ Generate Refresh Tokens with secure hashing for renewal.
- ๐ Generate ID Tokens for OpenID Connect-like scenarios.
- โ Validate refresh tokens for expiration and integrity.
- ๐ Supports RSA (asymmetric) or HMAC (symmetric) signing.
- ๐ Multi-Factor Authentication (MFA) compatible.
- โ๏ธ Fully configurable via strongly typed options classes (
JwtTokenOptionModel
orRsaTokenOptions
). - ๐งช Includes detailed exception handling for invalid or expired tokens.
๐ง Example Configuration (appsettings.json)
โ ๏ธ Security Tip: It's highly recommended to use environment variables to store sensitive values like file paths and keys instead of placing them directly in
appsettings.json
.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"RsaTokenOptions": {
"PrivateKeyPath": "/path/to/private.pem", // ๐ Prefer setting via environment variable
"PublicKeyPath": "/path/to/public.pem", // ๐ Prefer setting via environment variable
"Issuer": "https://auth.yourdomain.com",
"Audience": "https://api.yourdomain.com",
"AccessTokenLifetime": "00:30:00",
"RefreshTokenLifetime": "7.00:00:00",
"IdTokenLifetime": "00:15:00"
}
}
๐ Generate Access Token
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, "user123"),
new(JwtRegisteredClaimNames.Email, "user@example.com"),
};
string accessToken = tokenManager.GenerateAccessToken(claims);
๐ Generate Refresh Token
RefreshTokenModel refreshToken = tokenManager.GenerateRefreshToken();
๐ Generate ID Token
string idToken = tokenManager.GenerateIdToken(claims);
โ Validate Refresh Token
bool isValid = tokenManager.ValidateRefreshToken(refreshTokenFromClient);
๐ Security Notes
- Always store the hashed version of refresh tokens in your database.
- Configure your API to reject tampered JWTs by validating the RSA signature.
- If using
HMAC (HS256)
, make sure theSecretKey
is long and random (at least256 bits
). - Avoid long-lived access tokens โ use refresh tokens for session persistence.
๐งช Example: Token Response (from API)
{
"accessToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"idToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "af13uZ0-SOME-BASE64-VALUE-0qZn",
"expiresIn": 1800
}
๐งฉ Integration with ASP.NET Core
โ Option 1: RSA (Asymmetric) Integration โ RS256
This is the most secure option, using a private key to sign tokens and a public key to validate them.
Program.cs Example
var rsaPublic = RSA.Create();
rsaPublic.ImportFromPem(File.ReadAllText(configuration["RsaTokenOptions:PublicKeyPath"]));
builder.Services.Configure<RsaTokenOptions>(configuration.GetSection("RsaTokenOptions"));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
RequireExpirationTime = true,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero,
ValidIssuer = configuration["RsaTokenOptions:Issuer"],
ValidAudience = configuration["RsaTokenOptions:Audience"],
IssuerSigningKey = new RsaSecurityKey(rsaPublic)
};
});
๐ Option 2: HMAC (Symmetric) Integration โ HS256
Use this option if you're not using RSA keys. It's easier to set up but the SecretKey must remain private and secure.
Program.cs Example
var secretKey = configuration["JwtTokenOptionModel:SecretKey"];
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
builder.Services.Configure<TokenOptionModel>(configuration.GetSection("TokenOptionModel"));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
RequireExpirationTime = true,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero,
ValidIssuer = configuration["JwtTokenOptionModel:Issuer"],
ValidAudience = configuration["JwtTokenOptionModel:Audience"],
IssuerSigningKey = key
};
});
Register in Program.cs
// RSA (Asymmetric)
builder.Services.Configure<RsaTokenOptions>(
builder.Configuration.GetSection("RsaTokenOptions"));
builder.Services.AddScoped<RsaTokenManager>();
// HMAC (Symmetric)
builder.Services.Configure<TokenOptionModel>(
builder.Configuration.GetSection("JwtTokenOptionModel"));
builder.Services.AddScoped<JwtTokenManager>();
๐ฆ Installation
Install the package via NuGet:
dotnet add package Identity.Jwt.Token.Manager
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | 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. |
-
net9.0
- Microsoft.Extensions.Options (>= 9.0.3)
- System.IdentityModel.Tokens.Jwt (>= 8.7.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Notes Initial release of JwtTokenManager. Includes access token, refresh token, and ID token generation, validation, and secure hashing with .NET 9.0 support.