JwtTokenService 1.0.0
dotnet add package JwtTokenService --version 1.0.0
NuGet\Install-Package JwtTokenService -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="JwtTokenService" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="JwtTokenService" Version="1.0.0" />
<PackageReference Include="JwtTokenService" />
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 JwtTokenService --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: JwtTokenService, 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 JwtTokenService@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=JwtTokenService&version=1.0.0
#tool nuget:?package=JwtTokenService&version=1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
JWT Token Service for ASP.NET Core
A self-contained JWT token service library for ASP.NET Core applications that simplifies token generation, validation, and management.
Features
- Simple JWT token generation with customizable claims
- Token validation and verification
- Token refreshing
- Easy integration with ASP.NET Core dependency injection
- Configurable via appsettings.json or code
- Full support for user roles and custom claims
Installation
Package Manager Console
Install-Package JwtTokenService
.NET CLI
dotnet add package JwtTokenService
Quick Start
Step 1: Configure JWT settings in appsettings.json
{
"Jwt": {
"SecretKey": "your-secure-secret-key-with-at-least-32-characters",
"Issuer": "your-application",
"Audience": "your-clients",
"ExpirationInMinutes": 60
}
}
Step 2: Register the JWT Token Service in Program.cs
// Add JWT token service to the application
builder.Services.AddJwtTokenService(builder.Configuration);
// Or configure JWT options manually
builder.Services.AddJwtTokenService(options => {
options.SecretKey = "your-secure-secret-key-with-at-least-32-characters";
options.Issuer = "your-application";
options.Audience = "your-clients";
options.ExpirationInMinutes = 60;
});
Step 3: Configure JWT Authentication
var jwtOptions = builder.Configuration.GetSection("Jwt").Get<JwtOptions>()
?? throw new InvalidOperationException("JWT options not configured");
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecretKey)),
ValidateIssuer = !string.IsNullOrEmpty(jwtOptions.Issuer),
ValidIssuer = jwtOptions.Issuer,
ValidateAudience = !string.IsNullOrEmpty(jwtOptions.Audience),
ValidAudience = jwtOptions.Audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddAuthorization();
Step 4: Use the JWT Token Service in your controllers
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IJwtTokenService _jwtTokenService;
public AuthController(IJwtTokenService jwtTokenService)
{
_jwtTokenService = jwtTokenService;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginRequest request)
{
// Validate user credentials
if (IsValidUser(request.Username, request.Password))
{
var userId = GetUserId(request.Username);
var roles = GetUserRoles(request.Username);
// Generate the JWT token
var token = _jwtTokenService.GenerateToken(userId, request.Username, roles);
return Ok(new { token });
}
return Unauthorized();
}
}
Step 5: Protect your endpoints with the [Authorize] attribute
[Authorize]
[HttpGet("protected")]
public IActionResult Protected()
{
var userId = User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value;
var username = User.FindFirst(JwtRegisteredClaimNames.Name)?.Value;
return Ok(new { message = $"Hello, {username}!" });
}
[Authorize(Roles = "Admin")]
[HttpGet("admin-only")]
public IActionResult AdminOnly()
{
return Ok(new { message = "You are an admin!" });
}
API Reference
JwtOptions
Configuration options for the JWT token service.
SecretKey
- The secret key used to sign the JWT tokenIssuer
- The issuer of the JWT tokenAudience
- The audience of the JWT tokenExpirationInMinutes
- The expiration time in minutes (default: 60)
IJwtTokenService
GenerateToken(string userId, string username, IEnumerable<string> roles = null, IDictionary<string, string> additionalClaims = null)
- Generates a JWT token for the specified userValidateToken(string token)
- Validates a JWT tokenGetClaimsFromToken(string token)
- Gets the claims from a JWT tokenRefreshToken(string token)
- Refreshes a JWT token
Best Practices
- Use a strong secret key (at least 32 characters) and keep it secure
- Store the secret key in a secure location (e.g., Azure Key Vault, User Secrets)
- Set appropriate expiration times for your tokens
- Always validate tokens on protected endpoints
- Use HTTPS to transmit tokens
License
This project is licensed under the MIT License - see the LICENSE file for details.
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. 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.
-
net9.0
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.3)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.3)
- System.IdentityModel.Tokens.Jwt (>= 8.0.1)
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 | 176 | 4/3/2025 |