diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 556e249..590ab40 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,3 +37,9 @@ jobs: name: test-results-${{ matrix.os }}-${{ matrix.dotnet-version }} path: src/MiniJwt.Tests/TestResults/*.trx + - name: Build samples + run: | + dotnet build samples/ConsoleMinimal/ConsoleMinimal.csproj -c Release + dotnet build samples/ASPNetCoreAuth/ASPNetCoreAuth.csproj -c Release + dotnet build samples/WorkerService/WorkerService.csproj -c Release + diff --git a/README.md b/README.md index 8f99406..e1454a7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# MiniJwt.Core +# MiniJwt.Core [![CI](https://img.shields.io/github/actions/workflow/status/jeanlrnt/MiniJwt.Core/ci.yml?label=CI&style=flat-square&logo=github)](https://github.com/jeanlrnt/MiniJwt.Core/actions) @@ -16,9 +16,22 @@ [![License](https://img.shields.io/github/license/jeanlrnt/MiniJwt.Core?style=flat-square)](https://github.com/jeanlrnt/MiniJwt.Core/blob/main/LICENSE) [![Last commit](https://img.shields.io/github/last-commit/jeanlrnt/MiniJwt.Core?style=flat-square)](https://github.com/jeanlrnt/MiniJwt.Core/commits) -MiniJwt.Core is a small library for generating and validating JWTs using attributes on object properties to define claims. +MiniJwt.Core is a lightweight, minimal JWT library for .NET that provides a simple and efficient way to generate and validate JWT tokens using attributes on object properties to define claims. It's designed to be dependency-injection friendly, multi-target framework compatible, and easy to integrate. -This README shows how to install the package, register it in the DI of a .NET application, and provides usage examples (generation, validation and deserialization). It also contains tips for unit tests and debugging. +## Documentation + +**[Getting Started Guide](docs/getting-started.md)** - Installation and quick start +**[Configuration Guide](docs/configuration.md)** - Detailed configuration options +**[Examples](docs/examples.md)** - Code examples and integration patterns +**[FAQ](docs/faq.md)** - Common questions and security best practices + +## Sample Applications + +The repository includes three runnable sample applications demonstrating different integration scenarios: + +- **[ConsoleMinimal](samples/ConsoleMinimal/)** - Basic console app for token generation and validation +- **[ASPNetCoreAuth](samples/ASPNetCoreAuth/)** - Full ASP.NET Core web API with JWT authentication +- **[WorkerService](samples/WorkerService/)** - Background service example with periodic token generation ## Requirements @@ -150,7 +163,31 @@ var options = Options.Create(new MiniJwtOptions ExpirationMinutes = 60 }); -var svc = new MiniJwtService(options, NullLogger.Instance); +var svc = new MiniJwtService(options, NullLogger.Instance, new JwtSecurityTokenHandler()); +``` + +### Testing with TimeProvider + +For testable time-dependent behavior, the library supports `TimeProvider` (built-in for .NET 8+ or via `Microsoft.Bcl.TimeProvider` for earlier versions). You can inject a `FakeTimeProvider` for deterministic testing: + +```csharp +using Microsoft.Extensions.Time.Testing; + +var fakeTimeProvider = new FakeTimeProvider(); +fakeTimeProvider.SetUtcNow(new DateTimeOffset(2024, 1, 15, 10, 0, 0, TimeSpan.Zero)); + +var svc = new MiniJwtService( + options, + NullLogger.Instance, + new JwtSecurityTokenHandler(), + fakeTimeProvider +); + +// Generate token at the fixed time +var token = svc.GenerateToken(user); + +// Advance time for further testing +fakeTimeProvider.Advance(TimeSpan.FromMinutes(5)); ``` ## Debugging tips @@ -172,13 +209,31 @@ A: You can use `/p:PackageVersion=1.2.3` with `dotnet pack` or pack from a proje **Q: Why does `ValidateAndDeserialize` require `T` to have a parameterless constructor?** A: The service creates an instance of `T` using the parameterless constructor and then assigns properties from the claims. +## Contributing + +Contributions are welcome! Please: +- Follow the existing code style +- Add tests for new features +- Update documentation as needed +- Keep the library minimal and focused + +See the [examples documentation](docs/examples.md) for development guidelines. + ## Support -If you encounter issues, open an issue on the GitHub repository with: +If you encounter issues: + +1. Check the [FAQ](docs/faq.md) +2. Review the [sample applications](samples/) +3. Search [existing issues](https://github.com/jeanlrnt/MiniJwt.Core/issues) +4. Open a new issue with: + - .NET version used + - Minimal reproduction code + - Logs/stacktraces + +## License -- the .NET version used -- a minimal reproduction -- logs/stacktraces +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. --- diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..f472b3f --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,304 @@ +# Configuration Guide + +This guide explains all configuration options available in MiniJwt.Core and best practices for different scenarios. + +## MiniJwtOptions + +The `MiniJwtOptions` class provides the following configuration properties: + +### SecretKey + +**Type:** `string` +**Required:** Yes +**Default:** Empty string + +The secret key used for signing JWT tokens with the HMAC-SHA256 (HS256) algorithm. + +**Requirements:** +- Must be at least 32 bytes (256 bits) for HS256 +- Should be a securely generated random string +- Must be kept confidential and never committed to source control + +**Example:** +```csharp +options.SecretKey = "your-secret-key-at-least-32-bytes-long-for-hs256-algorithm"; +``` + +**Security Best Practice:** +```csharp +// Load from environment variables +options.SecretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY"); + +// Or from Azure Key Vault, AWS Secrets Manager, etc. +``` + +### Issuer + +**Type:** `string` +**Required:** No (but recommended) +**Default:** Empty string + +The issuer claim (`iss`) identifies the principal that issued the JWT. This is typically your application's name or URL. + +**Example:** +```csharp +options.Issuer = "https://api.myapp.com"; +// or +options.Issuer = "MyApplicationName"; +``` + +**Validation:** +- When set, tokens will be validated to ensure they were issued by this issuer +- When empty, issuer validation is disabled + +### Audience + +**Type:** `string` +**Required:** No (but recommended) +**Default:** Empty string + +The audience claim (`aud`) identifies the recipients that the JWT is intended for. This is typically your API or client application identifier. + +**Example:** +```csharp +options.Audience = "https://api.myapp.com"; +// or +options.Audience = "MyClientApp"; +``` + +**Validation:** +- When set, tokens will be validated to ensure they are intended for this audience +- When empty, audience validation is disabled + +### ExpirationMinutes + +**Type:** `double` +**Required:** No +**Default:** 60 minutes + +The lifetime of generated tokens in minutes. After this time, tokens will be considered expired and validation will fail. + +**Example:** +```csharp +options.ExpirationMinutes = 60; // 1 hour +options.ExpirationMinutes = 1440; // 24 hours +options.ExpirationMinutes = 0.5; // 30 seconds +``` + +**Best Practices:** +- Use shorter lifetimes (15-60 minutes) for access tokens +- Implement refresh tokens for longer sessions +- Consider your security requirements vs. user experience + +## Configuration Methods + +### 1. Using appsettings.json (Recommended) + +**appsettings.json:** +```json +{ + "MiniJwt": { + "SecretKey": "your-secret-key-here", + "Issuer": "MyApp", + "Audience": "MyClient", + "ExpirationMinutes": 60 + } +} +``` + +**Program.cs:** +```csharp +builder.Services.AddMiniJwt(options => +{ + var config = builder.Configuration.GetSection("MiniJwt"); + options.SecretKey = config["SecretKey"]; + options.Issuer = config["Issuer"]; + options.Audience = config["Audience"]; + options.ExpirationMinutes = double.Parse(config["ExpirationMinutes"] ?? "60"); +}); +``` + +### 2. Using IConfiguration Binding + +```csharp +builder.Services.Configure( + builder.Configuration.GetSection("MiniJwt")); + +builder.Services.AddMiniJwt(options => +{ + // Options are bound from configuration automatically +}); +``` + +### 3. Direct Configuration + +```csharp +builder.Services.AddMiniJwt(options => +{ + options.SecretKey = "my-secret-key-at-least-32-bytes-long"; + options.Issuer = "MyApp"; + options.Audience = "MyClient"; + options.ExpirationMinutes = 120; +}); +``` + +### 4. Environment-Based Configuration + +**appsettings.Development.json:** +```json +{ + "MiniJwt": { + "SecretKey": "development-secret-key-at-least-32-bytes", + "Issuer": "MyApp-Dev", + "Audience": "MyClient-Dev", + "ExpirationMinutes": 1440 + } +} +``` + +**appsettings.Production.json:** +```json +{ + "MiniJwt": { + "SecretKey": "", + "Issuer": "MyApp", + "Audience": "MyClient", + "ExpirationMinutes": 60 + } +} +``` + +**Program.cs (loading secret from environment):** +```csharp +builder.Services.AddMiniJwt(options => +{ + var config = builder.Configuration.GetSection("MiniJwt"); + + // Load secret from environment variable in production + options.SecretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY") + ?? config["SecretKey"]; + options.Issuer = config["Issuer"]; + options.Audience = config["Audience"]; + options.ExpirationMinutes = double.Parse(config["ExpirationMinutes"] ?? "60"); +}); +``` + +## Multi-Tenant Configuration + +For applications serving multiple tenants with different JWT configurations: + +```csharp +public class TenantJwtService +{ + private readonly Dictionary _services = new(); + + public TenantJwtService(IServiceProvider serviceProvider) + { + // Register services for each tenant + _services["tenant1"] = CreateServiceForTenant("tenant1", serviceProvider); + _services["tenant2"] = CreateServiceForTenant("tenant2", serviceProvider); + } + + private IMiniJwtService CreateServiceForTenant(string tenantId, IServiceProvider sp) + { + var options = new MiniJwtOptions + { + SecretKey = GetSecretForTenant(tenantId), + Issuer = $"MyApp-{tenantId}", + Audience = $"MyClient-{tenantId}", + ExpirationMinutes = 60 + }; + + return new MiniJwtService( + Options.CreateMonitor(Options.Create(options)), + sp.GetRequiredService>(), + new JwtSecurityTokenHandler { MapInboundClaims = false } + ); + } + + public IMiniJwtService GetServiceForTenant(string tenantId) + { + return _services.TryGetValue(tenantId, out var service) + ? service + : throw new InvalidOperationException($"Unknown tenant: {tenantId}"); + } +} +``` + +## Configuration Validation + +MiniJwt.Core includes built-in validation that runs on startup: + +- Validates that `SecretKey` is not empty +- Validates that `SecretKey` is at least 32 bytes for HS256 +- Validates that `ExpirationMinutes` is positive + +**Validation errors will prevent application startup** when using `ValidateOnStart()` (which is enabled by default when using `AddMiniJwt`). + +## Dynamic Configuration Updates + +MiniJwt.Core supports runtime configuration updates using `IOptionsMonitor`: + +```csharp +public class ConfigurationUpdateService : IHostedService +{ + private readonly IOptionsMonitor _optionsMonitor; + private IDisposable _listener; + + public ConfigurationUpdateService(IOptionsMonitor optionsMonitor) + { + _optionsMonitor = optionsMonitor; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + _listener = _optionsMonitor.OnChange(options => + { + Console.WriteLine("JWT configuration updated!"); + // MiniJwtService automatically picks up the changes + }); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + _listener?.Dispose(); + return Task.CompletedTask; + } +} +``` + +## Common Configuration Patterns + +### Short-Lived Access Tokens + +```csharp +options.ExpirationMinutes = 15; // 15 minutes +``` + +Use with a refresh token mechanism for secure, long-lived sessions. + +### Development/Testing + +```csharp +#if DEBUG +options.ExpirationMinutes = 1440; // 24 hours for easier debugging +#else +options.ExpirationMinutes = 60; // 1 hour in production +#endif +``` + +### API Gateway Integration + +```csharp +options.Issuer = "https://api-gateway.company.com"; +options.Audience = "microservice-a"; +``` + +Each microservice can use the same issuer but different audiences. + +## Next Steps + +- Learn about [practical examples](examples.md) +- Read [security best practices](faq.md#security-best-practices) +- Explore [sample applications](../samples/) diff --git a/docs/examples.md b/docs/examples.md new file mode 100644 index 0000000..663d9a6 --- /dev/null +++ b/docs/examples.md @@ -0,0 +1,524 @@ +# Examples + +This page provides practical examples and links to runnable sample applications demonstrating MiniJwt.Core in different scenarios. + +## Quick Examples + +### Basic Token Generation and Validation + +```csharp +using MiniJwt.Core.Attributes; +using MiniJwt.Core.Services; + +// 1. Define your payload model +public class UserClaims +{ + [MiniJwtClaim("sub")] + public string UserId { get; set; } + + [MiniJwtClaim("email")] + public string Email { get; set; } + + [MiniJwtClaim("role")] + public string Role { get; set; } +} + +// 2. Generate a token +var payload = new UserClaims +{ + UserId = "123", + Email = "user@example.com", + Role = "admin" +}; + +var token = jwtService.GenerateToken(payload); + +// 3. Validate the token +var principal = jwtService.ValidateToken(token); +if (principal != null) +{ + var userId = principal.FindFirst("sub")?.Value; + Console.WriteLine($"Valid token for user: {userId}"); +} +``` + +### Using Validate and Deserialize + +```csharp +var token = "your.jwt.token.here"; + +// Validate and automatically deserialize to your model +var user = jwtService.ValidateAndDeserialize(token); + +if (user != null) +{ + Console.WriteLine($"User: {user.Email}, Role: {user.Role}"); +} +else +{ + Console.WriteLine("Invalid or expired token"); +} +``` + +## ASP.NET Core Integration + +### Minimal API with Authentication + +```csharp +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using MiniJwt.Core.Extensions; +using System.Text; + +var builder = WebApplication.CreateBuilder(args); + +// Add MiniJwt +builder.Services.AddMiniJwt(options => +{ + options.SecretKey = builder.Configuration["MiniJwt:SecretKey"]; + options.Issuer = builder.Configuration["MiniJwt:Issuer"]; + options.Audience = builder.Configuration["MiniJwt:Audience"]; + options.ExpirationMinutes = 60; +}); + +// Add JWT Authentication +var key = Encoding.UTF8.GetBytes(builder.Configuration["MiniJwt:SecretKey"]); +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = true, + ValidIssuer = builder.Configuration["MiniJwt:Issuer"], + ValidateAudience = true, + ValidAudience = builder.Configuration["MiniJwt:Audience"], + ClockSkew = TimeSpan.Zero + }; + }); + +builder.Services.AddAuthorization(); + +var app = builder.Build(); + +app.UseAuthentication(); +app.UseAuthorization(); + +// Login endpoint +app.MapPost("/login", (IMiniJwtService jwtService) => +{ + var payload = new { sub = "user123", email = "user@example.com", role = "admin" }; + var token = jwtService.GenerateToken(payload); + return Results.Ok(new { token }); +}); + +// Protected endpoint +app.MapGet("/protected", () => "This is protected!") + .RequireAuthorization(); + +app.Run(); +``` + +### Controller-Based API + +```csharp +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using MiniJwt.Core.Services; + +[ApiController] +[Route("api/[controller]")] +public class AuthController : ControllerBase +{ + private readonly IMiniJwtService _jwtService; + private readonly ILogger _logger; + + public AuthController(IMiniJwtService jwtService, ILogger logger) + { + _jwtService = jwtService; + _logger = logger; + } + + [HttpPost("login")] + public IActionResult Login([FromBody] LoginRequest request) + { + // Validate credentials (implement your own logic) + if (!ValidateCredentials(request.Username, request.Password)) + { + return Unauthorized(new { message = "Invalid credentials" }); + } + + var payload = new UserPayload + { + UserId = "user123", + Email = request.Username, + Role = "user" + }; + + var token = _jwtService.GenerateToken(payload); + + if (token == null) + { + _logger.LogError("Failed to generate JWT token"); + return StatusCode(500, new { message = "Token generation failed" }); + } + + return Ok(new { token, expiresIn = 3600 }); + } + + [Authorize] + [HttpGet("me")] + public IActionResult GetCurrentUser() + { + var userId = User.FindFirst("sub")?.Value; + var email = User.FindFirst("email")?.Value; + var role = User.FindFirst("role")?.Value; + + return Ok(new { userId, email, role }); + } + + [Authorize(Roles = "admin")] + [HttpGet("admin")] + public IActionResult AdminOnly() + { + return Ok(new { message = "Admin access granted" }); + } + + private bool ValidateCredentials(string username, string password) + { + // WARNING: This is a placeholder. Implement real credential validation (e.g., check a user store, hash comparison, etc.). + // For safety, the default implementation always rejects the credentials. + return false; + } +} + +public record LoginRequest(string Username, string Password); +``` + +## Console Application + +See [samples/ConsoleMinimal](../samples/ConsoleMinimal/) for a complete runnable example. + +```csharp +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using MiniJwt.Core.Models; +using MiniJwt.Core.Services; +using System.IdentityModel.Tokens.Jwt; + +var options = Options.Create(new MiniJwtOptions +{ + SecretKey = "super-secret-key-at-least-32-bytes-long-hs256", + Issuer = "ConsoleApp", + Audience = "ConsoleClient", + ExpirationMinutes = 1 +}); + +var tokenHandler = new JwtSecurityTokenHandler { MapInboundClaims = false }; +var jwtService = new MiniJwtService( + Options.CreateMonitor(options), + NullLogger.Instance, + tokenHandler +); + +// Generate token +var token = jwtService.GenerateToken(new { sub = "user1", role = "admin" }); +Console.WriteLine($"Token: {token}"); + +// Validate immediately +var principal = jwtService.ValidateToken(token); +Console.WriteLine($"Valid: {principal?.Identity?.Name ?? "null"}"); + +// Wait for expiration +Console.WriteLine("Waiting for token to expire..."); +await Task.Delay(TimeSpan.FromSeconds(65)); + +// Validate expired token +var expiredPrincipal = jwtService.ValidateToken(token); +Console.WriteLine($"After expiration: {(expiredPrincipal == null ? "Invalid" : "Valid")}"); +``` + +## Worker Service / Background Service + +See [samples/WorkerService](../samples/WorkerService/) for a complete runnable example. + +```csharp +using MiniJwt.Core.Services; + +public class TokenGeneratorWorker : BackgroundService +{ + private readonly IMiniJwtService _jwtService; + private readonly ILogger _logger; + + public TokenGeneratorWorker( + IMiniJwtService jwtService, + ILogger logger) + { + _jwtService = jwtService; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + var payload = new + { + sub = $"worker-{Guid.NewGuid()}", + timestamp = DateTime.UtcNow.ToString("O") + }; + + var token = _jwtService.GenerateToken(payload); + + if (token != null) + { + _logger.LogInformation("Generated token: {Token}", token[..50] + "..."); + + // Validate it + var principal = _jwtService.ValidateToken(token); + _logger.LogInformation("Token validation: {Result}", + principal != null ? "Success" : "Failed"); + } + + await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error in token generation worker"); + await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); + } + } + } +} +``` + +## Advanced Scenarios + +### Custom Claims with Different Types + +```csharp +using MiniJwt.Core.Attributes; + +public class ExtendedPayload +{ + [MiniJwtClaim("sub")] + public string UserId { get; set; } + + [MiniJwtClaim("age")] + public int Age { get; set; } + + [MiniJwtClaim("premium")] + public bool IsPremium { get; set; } + + [MiniJwtClaim("balance")] + public decimal Balance { get; set; } + + [MiniJwtClaim("lastLogin")] + public DateTime? LastLogin { get; set; } +} + +// MiniJwt.Core automatically converts types when deserializing +var payload = new ExtendedPayload +{ + UserId = "user123", + Age = 30, + IsPremium = true, + Balance = 1234.56m, + LastLogin = DateTime.UtcNow +}; + +var token = jwtService.GenerateToken(payload); +var deserialized = jwtService.ValidateAndDeserialize(token); +``` + +### Middleware for Automatic Token Validation + +```csharp +public class JwtValidationMiddleware +{ + private readonly RequestDelegate _next; + private readonly IMiniJwtService _jwtService; + + public JwtValidationMiddleware(RequestDelegate next, IMiniJwtService jwtService) + { + _next = next; + _jwtService = jwtService; + } + + public async Task InvokeAsync(HttpContext context) + { + var token = context.Request.Headers["Authorization"] + .FirstOrDefault()?.Replace("Bearer ", ""); + + if (!string.IsNullOrEmpty(token)) + { + var principal = _jwtService.ValidateToken(token); + if (principal != null) + { + context.User = principal; + } + } + + await _next(context); + } +} + +// Register in Program.cs +app.UseMiddleware(); +``` + +### Unit Testing + +```csharp +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Xunit; + +public class JwtServiceTests +{ + private IMiniJwtService CreateService() + { + var options = Options.Create(new MiniJwtOptions + { + SecretKey = "test-secret-key-at-least-32-bytes-long", + Issuer = "TestApp", + Audience = "TestClient", + ExpirationMinutes = 60 + }); + + return new MiniJwtService( + Options.CreateMonitor(options), + NullLogger.Instance, + new JwtSecurityTokenHandler { MapInboundClaims = false } + ); + } + + [Fact] + public void GenerateToken_ValidPayload_ReturnsToken() + { + var service = CreateService(); + var token = service.GenerateToken(new { sub = "test" }); + + Assert.NotNull(token); + Assert.NotEmpty(token); + } + + [Fact] + public void ValidateToken_ValidToken_ReturnsPrincipal() + { + var service = CreateService(); + var token = service.GenerateToken(new { sub = "test123" }); + + var principal = service.ValidateToken(token); + + Assert.NotNull(principal); + Assert.Equal("test123", principal.FindFirst("sub")?.Value); + } +} +``` + +### Testing with TimeProvider for Deterministic Time + +```csharp +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; +using System.IdentityModel.Tokens.Jwt; +using Xunit; + +public class JwtServiceTimeTests +{ + // Simple test helper for IOptionsMonitor + private class SimpleOptionsMonitor(T value) : IOptionsMonitor + { + public T CurrentValue => value; + public T Get(string? name) => value; + public IDisposable OnChange(Action listener) => new NoOpDisposable(); + } + + private class NoOpDisposable : IDisposable + { + public void Dispose() { } + } + + [Fact] + public void GenerateToken_WithFakeTimeProvider_UsesProvidedTime() + { + // Arrange: Set up a fake time provider at a specific time + var fakeTimeProvider = new FakeTimeProvider(); + var fixedTime = new DateTimeOffset(2024, 1, 15, 10, 30, 0, TimeSpan.Zero); + fakeTimeProvider.SetUtcNow(fixedTime); + + var options = new SimpleOptionsMonitor(new MiniJwtOptions + { + SecretKey = "test-secret-key-at-least-32-bytes-long", + Issuer = "TestApp", + Audience = "TestClient", + ExpirationMinutes = 60 + }); + + // Create service with fake time provider + var service = new MiniJwtService( + options, + NullLogger.Instance, + new JwtSecurityTokenHandler { MapInboundClaims = false }, + fakeTimeProvider + ); + + // Act: Generate a token + var token = service.GenerateToken(new { sub = "test-user" }); + + // Assert: Verify the token uses the fake time + var handler = new JwtSecurityTokenHandler(); + var jwtToken = handler.ReadJwtToken(token); + + Assert.Equal(fixedTime.UtcDateTime, jwtToken.ValidFrom); + Assert.Equal(fixedTime.AddMinutes(60).UtcDateTime, jwtToken.ValidTo); + + // Advance time and generate another token + fakeTimeProvider.Advance(TimeSpan.FromMinutes(10)); + var token2 = service.GenerateToken(new { sub = "test-user2" }); + + var jwtToken2 = handler.ReadJwtToken(token2); + Assert.Equal(fixedTime.AddMinutes(10).UtcDateTime, jwtToken2.ValidFrom); + } +} +``` + +## Runnable Sample Applications + +We provide complete, runnable sample applications in the repository: + +1. **[ConsoleMinimal](../samples/ConsoleMinimal/)** - Basic console app demonstrating token generation and validation +2. **[ASPNetCoreAuth](../samples/ASPNetCoreAuth/)** - Full ASP.NET Core web API with authentication +3. **[WorkerService](../samples/WorkerService/)** - Background service example + +### Running the Samples + +```bash +# Clone the repository +git clone https://github.com/jeanlrnt/MiniJwt.Core.git +cd MiniJwt.Core + +# Run Console sample +cd samples/ConsoleMinimal +dotnet run + +# Run ASP.NET Core sample +cd samples/ASPNetCoreAuth +dotnet run +# Then access https://localhost:5001/swagger + +# Run Worker Service sample +cd samples/WorkerService +dotnet run +``` + +## Next Steps + +- Review [configuration options](configuration.md) +- Read [security best practices](faq.md) +- Explore the [API documentation](https://www.nuget.org/packages/MiniJwt.Core) diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..7f0d78f --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,421 @@ +# Frequently Asked Questions (FAQ) + +## General Questions + +### What is MiniJwt.Core? + +MiniJwt.Core is a lightweight JWT library for .NET that provides a simple way to generate and validate JWT tokens using attributes on your model properties. It's designed to be minimal, dependency-injection friendly, and multi-target framework compatible. + +### What .NET versions are supported? + +MiniJwt.Core supports: +- .NET 6.0 +- .NET 7.0 +- .NET 8.0 +- .NET 9.0 +- .NET 10.0 + +### Is MiniJwt.Core thread-safe? + +Yes, the `MiniJwtService` implementation is thread-safe and can be registered as a singleton in the dependency injection container. + +### Can I use MiniJwt.Core in production? + +Yes, MiniJwt.Core is production-ready. However, always follow security best practices (see below) for key management, token lifetime, and secure communication. + +## Configuration Questions + +### Why does GenerateToken return null? + +The most common reasons are: + +1. **Secret key too short**: The `SecretKey` must be at least 32 bytes (256 bits) for HS256 algorithm +2. **Invalid configuration**: Check that your `MiniJwtOptions` are properly configured +3. **Exceptions during generation**: Enable logging to see detailed error messages + +```csharp +// Ensure your secret key is long enough +options.SecretKey = "your-secret-key-at-least-32-bytes-long-for-hs256"; +``` + +### How do I load the secret key from environment variables? + +```csharp +builder.Services.AddMiniJwt(options => +{ + options.SecretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY") + ?? throw new InvalidOperationException("JWT_SECRET_KEY not set"); + options.Issuer = builder.Configuration["MiniJwt:Issuer"]; + options.Audience = builder.Configuration["MiniJwt:Audience"]; +}); +``` + +### Can I use different configurations for different environments? + +Yes, use environment-specific `appsettings.json` files: + +- `appsettings.Development.json` - for development +- `appsettings.Production.json` - for production + +Or use environment variables for sensitive configuration like secret keys. + +### Can I change configuration at runtime? + +Yes, MiniJwt.Core uses `IOptionsMonitor` which supports runtime configuration updates. Changes to the configuration will be picked up automatically by the service. + +## Token Generation Questions + +### What claims are included in the token? + +MiniJwt.Core includes: +- All properties decorated with `[MiniJwtClaim]` attribute +- Standard JWT claims: `iss` (issuer), `aud` (audience), `nbf` (not before), `exp` (expiration), `jti` (JWT ID) + +### Can I add custom claims without using attributes? + +Currently, MiniJwt.Core uses attributes to map properties to claims. If you need more flexibility, you can: + +1. Create a wrapper payload object with attributed properties +2. Extend the library with a custom implementation +3. Use the underlying `System.IdentityModel.Tokens.Jwt` directly for advanced scenarios + +### How do I set the token expiration? + +Use the `ExpirationMinutes` option: + +```csharp +options.ExpirationMinutes = 60; // 1 hour +options.ExpirationMinutes = 1440; // 24 hours +options.ExpirationMinutes = 0.5; // 30 seconds +``` + +### What happens if I don't set Issuer or Audience? + +If `Issuer` or `Audience` are empty strings: +- The claims won't be included in the token +- Validation for these claims will be disabled + +For production use, it's **strongly recommended** to set both for proper token validation. + +## Token Validation Questions + +### Why does ValidateToken return null? + +Common reasons: + +1. **Token expired**: Check the `ExpirationMinutes` setting +2. **Wrong secret key**: Validation must use the same secret key as generation +3. **Issuer/Audience mismatch**: Ensure configuration matches between generation and validation +4. **Malformed token**: The token string may be corrupted or invalid +5. **Clock skew**: Token validation uses zero clock skew by default + +Enable logging to see detailed validation error messages. + +### How do I handle expired tokens? + +Tokens are automatically validated for expiration. When a token expires, `ValidateToken` returns `null`. + +**Best practice:** Implement a refresh token mechanism: + +```csharp +public class TokenResponse +{ + public string AccessToken { get; set; } + public string RefreshToken { get; set; } + public DateTime ExpiresAt { get; set; } +} + +// Store refresh tokens securely (database, Redis, etc.) +// Implement endpoint to exchange refresh token for new access token +``` + +### Can I validate tokens from external issuers? + +MiniJwt.Core is designed for generating and validating your own tokens. To validate tokens from external issuers (e.g., Azure AD, Auth0), use the standard ASP.NET Core JWT authentication middleware with appropriate configuration. + +## Security Best Practices + +### How should I manage the secret key? + +**DO:** +- ✅ Generate cryptographically random keys (at least 32 bytes) +- ✅ Store keys in secure secret management systems (Azure Key Vault, AWS Secrets Manager, HashiCorp Vault) +- ✅ Use environment variables for keys, never hardcode +- ✅ Rotate keys periodically +- ✅ Use different keys for different environments + +**DON'T:** +- ❌ Commit keys to source control +- ❌ Store keys in plain text in configuration files +- ❌ Use weak or predictable keys +- ❌ Share keys across unrelated applications +- ❌ Expose keys in logs or error messages + +### How do I generate a secure secret key? + +```bash +# Using openssl +openssl rand -base64 32 + +# Using PowerShell +[Convert]::ToBase64String((1..32 | ForEach-Object { Get-Random -Maximum 256 })) + +# Using C# +var key = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); +``` + +### What is the recommended token lifetime? + +**Access Tokens:** +- Short-lived: 15-60 minutes +- Reduces the impact of token theft +- Use refresh tokens for longer sessions + +**Refresh Tokens:** +- Long-lived: days to weeks +- Store securely on the backend +- Allow users to obtain new access tokens without re-authentication + +### How should I transmit tokens? + +**DO:** +- ✅ Use HTTPS/TLS for all communication +- ✅ Send tokens in the `Authorization` header: `Bearer {token}` +- ✅ Use secure, httpOnly cookies for web applications +- ✅ Implement token revocation mechanisms + +**DON'T:** +- ❌ Send tokens in URLs (they may be logged) +- ❌ Store tokens in localStorage (vulnerable to XSS) +- ❌ Transmit tokens over unencrypted connections + +### How do I implement key rotation? + +Key rotation ensures compromised keys have limited impact: + +```csharp +public class KeyRotationService +{ + private readonly List _keyHistory = new(); + + public void RotateKey(string newKey) + { + // Keep old key for validation of existing tokens + var oldOptions = GetCurrentOptions(); + _keyHistory.Add(oldOptions); + + // Update to new key for generation + UpdateOptions(new MiniJwtOptions + { + SecretKey = newKey, + // ... other options + }); + + // Remove keys older than max token lifetime + CleanupOldKeys(); + } + + public bool ValidateWithAnyKey(string token) + { + // Try current key first + if (ValidateWithCurrentKey(token)) return true; + + // Fall back to historical keys + return _keyHistory.Any(opts => ValidateWithKey(token, opts)); + } +} +``` + +### Should I validate tokens on every request? + +**For stateless APIs:** Yes, validate the token on every request. This is the standard approach for JWT-based authentication. + +**For stateful applications:** You may cache validation results in the user's session, but ensure proper session security and expiration handling. + +### How do I prevent token theft? + +1. **Use HTTPS**: Always transmit tokens over secure connections +2. **Short token lifetimes**: Limit the damage if tokens are stolen +3. **Token binding**: Bind tokens to specific clients or IP addresses (advanced) +4. **Refresh tokens**: Use short-lived access tokens with secure refresh mechanisms +5. **Monitoring**: Log and monitor for suspicious token usage patterns +6. **Revocation**: Implement a token revocation/blacklist mechanism if needed + +### What about XSS and CSRF attacks? + +**XSS (Cross-Site Scripting):** +- Don't store tokens in localStorage (use httpOnly cookies or memory) +- Sanitize all user input +- Use Content Security Policy (CSP) headers + +**CSRF (Cross-Site Request Forgery):** +- When using cookies, implement CSRF protection (anti-forgery tokens) +- Using the `Authorization` header naturally protects against CSRF +- Validate the `Origin` or `Referer` headers + +### Should I store tokens in a database? + +**Generally no** for access tokens - JWT tokens are stateless by design. + +**Consider storing:** +- Refresh tokens (with secure hashing) +- Revocation lists for specific tokens +- Audit logs of token generation + +## Integration Questions + +### How do I integrate with ASP.NET Core authentication? + +See the [ASPNetCoreAuth sample](../samples/ASPNetCoreAuth/) for a complete example. In summary: + +1. Register MiniJwt with `AddMiniJwt()` +2. Configure JWT authentication with matching parameters +3. Use `[Authorize]` attributes on controllers/endpoints +4. Generate tokens in your login endpoint + +### Can I use MiniJwt.Core with Blazor? + +Yes, you can use MiniJwt.Core in Blazor Server or in the API backend for Blazor WebAssembly. For Blazor WebAssembly, you'll typically: + +1. Generate tokens in your API (using MiniJwt.Core) +2. Send tokens to the Blazor client +3. Include tokens in API requests from the client +4. Validate tokens in the API (using MiniJwt.Core) + +### Can I use MiniJwt.Core with gRPC? + +Yes, generate tokens with MiniJwt.Core and include them in gRPC metadata: + +```csharp +var metadata = new Metadata +{ + { "Authorization", $"Bearer {token}" } +}; + +var call = client.MyRpcMethod(request, metadata); +``` + +Validate tokens in your gRPC service using ASP.NET Core authentication middleware. + +### How do I test code that uses MiniJwt.Core? + +See the [examples documentation](examples.md#unit-testing) for unit testing patterns. Key points: + +- Create test instances with `NullLogger.Instance` +- Use `Options.Create()` for test configurations +- Mock `IMiniJwtService` in your tests for isolation +- Use `FakeTimeProvider` from `Microsoft.Extensions.TimeProvider.Testing` for deterministic time-dependent testing + +For time-dependent testing, inject a `FakeTimeProvider` into the service constructor to control token generation timestamps. See [Testing with TimeProvider](examples.md#testing-with-timeprovider-for-deterministic-time) for examples. + +## Troubleshooting + +### Logging is not showing JWT errors + +Ensure logging is properly configured: + +```csharp +builder.Logging.AddConsole(); +builder.Logging.SetMinimumLevel(LogLevel.Debug); +``` + +Or in `appsettings.json`: + +```json +{ + "Logging": { + "LogLevel": { + "MiniJwt.Core": "Debug" + } + } +} +``` + +### Tokens are not validating after deployment + +Common issues: +- Secret key differs between environments +- Issuer/Audience configuration mismatch +- System clock differences (ensure NTP synchronization) +- Configuration not loading correctly + +### How can I debug token contents? + +Visit [jwt.io](https://jwt.io/) and paste your token to decode and inspect its claims. **Never paste production tokens with real user data on public websites.** + +For debugging in code: + +```csharp +var handler = new JwtSecurityTokenHandler(); +var jsonToken = handler.ReadToken(token) as JwtSecurityToken; +var claims = jsonToken?.Claims.ToList(); +// Inspect claims for debugging +``` + +## Performance Questions + +### What is the performance overhead? + +MiniJwt.Core is very lightweight: +- Token generation: ~1-5ms depending on payload size +- Token validation: ~1-3ms +- Memory footprint: Minimal (stateless service) + +The service can be safely registered as a singleton for optimal performance. + +### Can MiniJwt.Core handle high load? + +Yes, the service is thread-safe and designed for high-throughput scenarios. For very high loads: +- Register as singleton (recommended) +- Consider caching validation results if validating the same token multiple times +- Use connection pooling and async APIs in your application + +### Should I cache tokens? + +**For generation:** No need - generation is fast. + +**For validation:** For the same token being validated multiple times in a short period, you can cache the validation result, but ensure: +- Cache expires before the token +- Cache is properly secured +- You handle cache invalidation correctly + +## Contributing and Support + +### How do I report a bug? + +Open an issue on [GitHub](https://github.com/jeanlrnt/MiniJwt.Core/issues) with: +- .NET version +- MiniJwt.Core version +- Minimal reproduction code +- Expected vs actual behavior +- Any relevant logs or error messages + +### How do I request a feature? + +Open a feature request issue on GitHub. For better chances of implementation: +- Explain the use case and motivation +- Provide examples of how the feature would be used +- Consider if it fits the "minimal" philosophy of the library + +### Can I contribute? + +Yes! Contributions are welcome. Please: +- Follow the existing code style +- Add tests for new features +- Update documentation as needed +- Keep the library minimal and focused + +### Where can I get help? + +1. Check this FAQ +2. Review the [examples](examples.md) +3. Check existing [GitHub issues](https://github.com/jeanlrnt/MiniJwt.Core/issues) +4. Open a new issue with your question + +## Additional Resources + +- [Getting Started Guide](getting-started.md) +- [Configuration Guide](configuration.md) +- [Examples and Sample Applications](examples.md) +- [GitHub Repository](https://github.com/jeanlrnt/MiniJwt.Core) +- [NuGet Package](https://www.nuget.org/packages/MiniJwt.Core) diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..7d4c33e --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,232 @@ +# Getting Started with MiniJwt.Core + +MiniJwt.Core is a lightweight JWT (JSON Web Token) library for .NET that provides a simple and efficient way to generate and validate JWT tokens using attributes on your model properties. + +## Installation + +Install MiniJwt.Core via the .NET CLI: + +```bash +dotnet add package MiniJwt.Core +``` + +Or via the Package Manager Console in Visual Studio: + +```powershell +Install-Package MiniJwt.Core +``` + +## Requirements + +- .NET 6.0 or higher +- Support for .NET 6.0, 7.0, 8.0, 9.0, and 10.0 + +## Quick Start + +### 1. Define Your Payload Model + +Create a model class with properties decorated with the `[MiniJwtClaim]` attribute: + +```csharp +using MiniJwt.Core.Attributes; + +public class UserPayload +{ + [MiniJwtClaim("sub")] + public string UserId { get; set; } + + [MiniJwtClaim("email")] + public string Email { get; set; } + + [MiniJwtClaim("role")] + public string Role { get; set; } +} +``` + +### 2. Configure MiniJwt Options + +In your `appsettings.json`: + +```json +{ + "MiniJwt": { + "SecretKey": "your-secret-key-at-least-32-bytes-long-for-hs256-algorithm", + "Issuer": "YourAppName", + "Audience": "YourAppClient", + "ExpirationMinutes": 60 + } +} +``` + +### 3. Register MiniJwt in Dependency Injection + +In your `Program.cs`: + +```csharp +using MiniJwt.Core.Extensions; + +var builder = WebApplication.CreateBuilder(args); + +// Register MiniJwt with configuration +builder.Services.AddMiniJwt(options => +{ + var config = builder.Configuration.GetSection("MiniJwt"); + options.SecretKey = config["SecretKey"]; + options.Issuer = config["Issuer"]; + options.Audience = config["Audience"]; + options.ExpirationMinutes = double.Parse(config["ExpirationMinutes"] ?? "60"); +}); + +var app = builder.Build(); +app.Run(); +``` + +### 4. Generate a Token + +Inject `IMiniJwtService` into your controller or service: + +```csharp +using MiniJwt.Core.Services; + +public class AuthController : ControllerBase +{ + private readonly IMiniJwtService _jwtService; + + public AuthController(IMiniJwtService jwtService) + { + _jwtService = jwtService; + } + + [HttpPost("login")] + public IActionResult Login() + { + var payload = new UserPayload + { + UserId = "user123", + Email = "user@example.com", + Role = "admin" + }; + + var token = _jwtService.GenerateToken(payload); + + if (token == null) + { + return StatusCode(500, "Failed to generate token"); + } + + return Ok(new { token }); + } +} +``` + +### 5. Validate a Token + +```csharp +[HttpGet("protected")] +public IActionResult GetProtectedResource([FromHeader] string authorization) +{ + // Extract token from "Bearer {token}" + var token = authorization?.Replace("Bearer ", ""); + + var principal = _jwtService.ValidateToken(token); + + if (principal == null) + { + return Unauthorized(); + } + + // Access claims + var userId = principal.FindFirst("sub")?.Value; + return Ok(new { message = "Access granted", userId }); +} +``` + +### 6. Validate and Deserialize + +For direct object deserialization: + +```csharp +var token = "your.jwt.token"; +var user = _jwtService.ValidateAndDeserialize(token); + +if (user == null) +{ + // Invalid token or missing claims + return Unauthorized(); +} + +// Use user.UserId, user.Email, user.Role +return Ok(user); +``` + +## Console Application Example + +For a minimal console application without dependency injection: + +```csharp +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using MiniJwt.Core.Models; +using MiniJwt.Core.Services; +using System.IdentityModel.Tokens.Jwt; + +var options = new MiniJwtOptions +{ + SecretKey = "my-super-secret-key-at-least-32-bytes-long-hs256", + Issuer = "MyConsoleApp", + Audience = "MyConsoleClient", + ExpirationMinutes = 60 +}; + +// Create IOptionsMonitor for console usage +var optionsMonitor = Microsoft.Extensions.Options.Options.CreateMonitor(options); + +var tokenHandler = new JwtSecurityTokenHandler { MapInboundClaims = false }; +var jwtService = new MiniJwtService( + optionsMonitor, + NullLogger.Instance, + tokenHandler +); + +// Generate token +var payload = new { sub = "user1", role = "admin" }; +var token = jwtService.GenerateToken(payload); +Console.WriteLine($"Generated Token: {token}"); + +// Validate token +var principal = jwtService.ValidateToken(token); +if (principal != null) +{ + Console.WriteLine($"Token is valid! Subject: {principal.FindFirst("sub")?.Value}"); +} +``` + +See the [ConsoleMinimal sample](../samples/ConsoleMinimal/) for a complete working example. + +## Next Steps + +- Learn about [configuration options](configuration.md) +- Explore [practical examples](examples.md) +- Read the [FAQ and best practices](faq.md) +- Check out the [sample applications](../samples/) + +## Common Issues + +### Token Generation Returns Null + +The most common cause is a `SecretKey` that is too short. HS256 requires at least 32 bytes (256 bits). Make sure your secret key is at least 32 characters long. + +### Token Validation Fails + +Check that: +- The same `SecretKey` is used for both generation and validation +- The `Issuer` and `Audience` match between generation and validation +- The token has not expired +- Enable logging to see detailed error messages + +## Support + +If you encounter issues: +- Check the [FAQ](faq.md) +- Review the [samples](../samples/) +- Open an issue on [GitHub](https://github.com/jeanlrnt/MiniJwt.Core/issues) diff --git a/samples/ASPNetCoreAuth/ASPNetCoreAuth.csproj b/samples/ASPNetCoreAuth/ASPNetCoreAuth.csproj new file mode 100644 index 0000000..b7a0fca --- /dev/null +++ b/samples/ASPNetCoreAuth/ASPNetCoreAuth.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/samples/ASPNetCoreAuth/ASPNetCoreAuth.http b/samples/ASPNetCoreAuth/ASPNetCoreAuth.http new file mode 100644 index 0000000..9657b10 --- /dev/null +++ b/samples/ASPNetCoreAuth/ASPNetCoreAuth.http @@ -0,0 +1,55 @@ +@ASPNetCoreAuth_HostAddress = http://localhost:5030 + +# Get API information +GET {{ASPNetCoreAuth_HostAddress}}/ +Accept: application/json + +### + +# Login to get a JWT token +POST {{ASPNetCoreAuth_HostAddress}}/auth/login +Content-Type: application/json + +{ + "username": "testuser", + "password": "password" +} + +### + +# Get current user info (requires authentication) +# First, run the login request above and copy the token +GET {{ASPNetCoreAuth_HostAddress}}/auth/me +Authorization: Bearer YOUR_TOKEN_HERE + +### + +# Access public data (no authentication required) +GET {{ASPNetCoreAuth_HostAddress}}/data/public +Accept: application/json + +### + +# Access protected data (requires authentication) +GET {{ASPNetCoreAuth_HostAddress}}/data/protected +Authorization: Bearer YOUR_TOKEN_HERE + +### + +# Access admin-only data (requires admin role) +# Login as admin first +POST {{ASPNetCoreAuth_HostAddress}}/auth/login +Content-Type: application/json + +{ + "username": "admin", + "password": "password" +} + +### + +# Then access admin endpoint with admin token +GET {{ASPNetCoreAuth_HostAddress}}/data/admin +Authorization: Bearer YOUR_ADMIN_TOKEN_HERE + +### diff --git a/samples/ASPNetCoreAuth/Program.cs b/samples/ASPNetCoreAuth/Program.cs new file mode 100644 index 0000000..cb36b4d --- /dev/null +++ b/samples/ASPNetCoreAuth/Program.cs @@ -0,0 +1,184 @@ +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.IdentityModel.Tokens; +using MiniJwt.Core.Attributes; +using MiniJwt.Core.Extensions; +using MiniJwt.Core.Services; +using System.Text; + +var builder = WebApplication.CreateBuilder(args); + +// Add MiniJwt service +builder.Services.AddMiniJwt(options => +{ + var config = builder.Configuration.GetSection("MiniJwt"); + options.SecretKey = config["SecretKey"] ?? throw new InvalidOperationException("SecretKey not configured"); + options.Issuer = config["Issuer"] ?? "ASPNetCoreAuthSample"; + options.Audience = config["Audience"] ?? "ASPNetCoreAuthClient"; + options.ExpirationMinutes = double.Parse(config["ExpirationMinutes"] ?? "60"); +}); + +// Add JWT Authentication +var jwtConfig = builder.Configuration.GetSection("MiniJwt"); +var key = Encoding.UTF8.GetBytes(jwtConfig["SecretKey"] ?? throw new InvalidOperationException("SecretKey not configured")); + +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = true, + ValidIssuer = jwtConfig["Issuer"], + ValidateAudience = true, + ValidAudience = jwtConfig["Audience"], + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero + }; + }); + +builder.Services.AddAuthorization(); + +var app = builder.Build(); + +app.UseAuthentication(); +app.UseAuthorization(); + +// Public endpoint - Login +app.MapPost("/auth/login", (LoginRequest request, IMiniJwtService jwtService) => +{ + // In a real application, validate credentials against a database + if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password)) + { + return Results.BadRequest(new { message = "Username and password are required" }); + } + + // For demo purposes, accept any credentials + var payload = new UserPayload + { + UserId = Guid.NewGuid().ToString(), + Username = request.Username, + Email = $"{request.Username}@example.com", + Role = request.Username == "admin" ? "admin" : "user" + }; + + var token = jwtService.GenerateToken(payload); + + if (token == null) + { + return Results.StatusCode(500); + } + + return Results.Ok(new LoginResponse + { + Token = token, + ExpiresIn = 3600, + Username = payload.Username, + Role = payload.Role + }); +}) +.WithName("Login") +.WithDescription("Login endpoint - accepts any username/password for demo purposes"); + +// Public endpoint - Get current time +app.MapGet("/", () => new +{ + message = "MiniJwt.Core ASP.NET Core Auth Sample", + timestamp = DateTime.UtcNow, + endpoints = new[] + { + "POST /auth/login - Get a JWT token", + "GET /auth/me - Get current user info (requires auth)", + "GET /data/public - Public data endpoint", + "GET /data/protected - Protected data endpoint (requires auth)", + "GET /data/admin - Admin only endpoint (requires admin role)" + } +}) +.WithName("Root"); + +// Protected endpoint - Get current user +app.MapGet("/auth/me", (HttpContext context, IMiniJwtService jwtService) => +{ + var token = context.Request.Headers.Authorization.FirstOrDefault()?.Replace("Bearer ", ""); + + if (string.IsNullOrEmpty(token)) + { + return Results.Unauthorized(); + } + + var user = jwtService.ValidateAndDeserialize(token); + + if (user == null) + { + return Results.Unauthorized(); + } + + return Results.Ok(new + { + user.UserId, + user.Username, + user.Email, + user.Role + }); +}) +.RequireAuthorization() +.WithName("GetCurrentUser"); + +// Public endpoint +app.MapGet("/data/public", () => new +{ + message = "This is public data", + timestamp = DateTime.UtcNow +}) +.WithName("PublicData"); + +// Protected endpoint +app.MapGet("/data/protected", (HttpContext context) => new +{ + message = "This is protected data", + user = context.User.FindFirst("sub")?.Value, + timestamp = DateTime.UtcNow +}) +.RequireAuthorization() +.WithName("ProtectedData"); + +// Admin-only endpoint +app.MapGet("/data/admin", (HttpContext context) => new +{ + message = "This is admin-only data", + admin = context.User.FindFirst("username")?.Value, + timestamp = DateTime.UtcNow +}) +.RequireAuthorization(policy => policy.RequireClaim("role", "admin")) +.WithName("AdminData"); + +app.Run(); + +// Request/Response models +public record LoginRequest(string Username, string Password); + +public record LoginResponse +{ + public string Token { get; set; } = string.Empty; + public int ExpiresIn { get; set; } + public string Username { get; set; } = string.Empty; + public string Role { get; set; } = string.Empty; +} + +// User payload with MiniJwt attributes +public class UserPayload +{ + [MiniJwtClaim("sub")] + public string UserId { get; set; } = string.Empty; + + [MiniJwtClaim("username")] + public string Username { get; set; } = string.Empty; + + [MiniJwtClaim("email")] + public string Email { get; set; } = string.Empty; + + [MiniJwtClaim("role")] + public string Role { get; set; } = string.Empty; +} + + diff --git a/samples/ASPNetCoreAuth/Properties/launchSettings.json b/samples/ASPNetCoreAuth/Properties/launchSettings.json new file mode 100644 index 0000000..cf4b176 --- /dev/null +++ b/samples/ASPNetCoreAuth/Properties/launchSettings.json @@ -0,0 +1,42 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:56135", + "sslPort": 44328 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "", + "applicationUrl": "http://localhost:5030", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "", + "applicationUrl": "https://localhost:5001;http://localhost:5030", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} + diff --git a/samples/ASPNetCoreAuth/README.md b/samples/ASPNetCoreAuth/README.md new file mode 100644 index 0000000..4873f05 --- /dev/null +++ b/samples/ASPNetCoreAuth/README.md @@ -0,0 +1,210 @@ +# ASPNetCoreAuth Sample + +This sample demonstrates how to integrate MiniJwt.Core with ASP.NET Core for JWT-based authentication. + +## Features + +- Dependency injection registration with `AddMiniJwt()` +- JWT authentication middleware integration +- Login endpoint for token generation +- Protected endpoints requiring authentication +- Role-based authorization +- Public and private API endpoints + +## Running the Sample + +```bash +cd samples/ASPNetCoreAuth +dotnet run +``` + +The API will start on `https://localhost:5001` (or the port configured in launchSettings.json). + +## API Endpoints + +### Public Endpoints + +#### GET / - Root endpoint +```bash +curl https://localhost:5001/ +``` + +Returns information about available endpoints. + +#### POST /auth/login - Get JWT Token +```bash +curl -X POST https://localhost:5001/auth/login \ + -H "Content-Type: application/json" \ + -d '{"username": "testuser", "password": "password"}' +``` + +**Note:** For demo purposes, this endpoint accepts any username/password combination. + +Response: +```json +{ + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "expiresIn": 3600, + "username": "testuser", + "role": "user" +} +``` + +#### GET /data/public - Public data +```bash +curl https://localhost:5001/data/public +``` + +### Protected Endpoints (Require Authentication) + +#### GET /auth/me - Get current user info +```bash +curl https://localhost:5001/auth/me \ + -H "Authorization: Bearer YOUR_TOKEN_HERE" +``` + +#### GET /data/protected - Protected data +```bash +curl https://localhost:5001/data/protected \ + -H "Authorization: Bearer YOUR_TOKEN_HERE" +``` + +#### GET /data/admin - Admin-only data (requires admin role) +```bash +# Login as admin +curl -X POST https://localhost:5001/auth/login \ + -H "Content-Type: application/json" \ + -d '{"username": "admin", "password": "password"}' + +# Use the admin token +curl https://localhost:5001/data/admin \ + -H "Authorization: Bearer ADMIN_TOKEN_HERE" +``` + +## Configuration + +Configuration is in `appsettings.json`: + +```json +{ + "MiniJwt": { + "SecretKey": "sample-secret-key-at-least-32-bytes-long-for-hs256", + "Issuer": "ASPNetCoreAuthSample", + "Audience": "ASPNetCoreAuthClient", + "ExpirationMinutes": 60 + } +} +``` + +**Important:** In production, never hardcode the `SecretKey`. Use environment variables, Azure Key Vault, or other secure secret management solutions. + +## Key Integration Points + +### 1. Service Registration + +```csharp +builder.Services.AddMiniJwt(options => +{ + var config = builder.Configuration.GetSection("MiniJwt"); + options.SecretKey = config["SecretKey"]; + options.Issuer = config["Issuer"]; + options.Audience = config["Audience"]; + options.ExpirationMinutes = double.Parse(config["ExpirationMinutes"] ?? "60"); +}); +``` + +### 2. JWT Authentication Middleware + +```csharp +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = true, + ValidIssuer = jwtConfig["Issuer"], + ValidateAudience = true, + ValidAudience = jwtConfig["Audience"], + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero + }; + }); +``` + +### 3. Using IMiniJwtService + +```csharp +app.MapPost("/auth/login", (LoginRequest request, IMiniJwtService jwtService) => +{ + var payload = new UserPayload { /* ... */ }; + var token = jwtService.GenerateToken(payload); + return Results.Ok(new { token }); +}); +``` + +### 4. Protecting Endpoints + +```csharp +// Requires authentication +app.MapGet("/data/protected", () => { /* ... */ }) + .RequireAuthorization(); + +// Requires specific role +app.MapGet("/data/admin", () => { /* ... */ }) + .RequireAuthorization(policy => policy.RequireClaim("role", "admin")); +``` + +## Testing the Flow + +1. **Get a token:** + ```bash + TOKEN=$(curl -X POST https://localhost:5001/auth/login \ + -H "Content-Type: application/json" \ + -d '{"username": "testuser", "password": "password"}' \ + -s | jq -r .token) + ``` + +2. **Use the token:** + ```bash + curl https://localhost:5001/auth/me \ + -H "Authorization: Bearer $TOKEN" + ``` + +3. **Try without token (will fail):** + ```bash + curl https://localhost:5001/data/protected + # Returns 401 Unauthorized + ``` + +## Production Considerations + +1. **Secret Key Management:** + - Use environment variables or secret managers + - Rotate keys regularly + - Never commit secrets to source control + +2. **HTTPS:** + - Always use HTTPS in production + - The sample uses HTTPS by default + +3. **Token Lifetime:** + - Use shorter lifetimes (15-60 minutes) for access tokens + - Implement refresh token mechanism for longer sessions + +4. **Credential Validation:** + - This sample accepts any credentials for demo purposes + - In production, validate against a secure database + - Hash passwords using bcrypt or similar + +5. **Error Handling:** + - Add proper error handling and logging + - Don't leak sensitive information in error messages + +## Related Documentation + +- [Getting Started Guide](../../docs/getting-started.md) +- [Configuration Guide](../../docs/configuration.md) +- [Examples](../../docs/examples.md) +- [Security FAQ](../../docs/faq.md#security-best-practices) diff --git a/samples/ASPNetCoreAuth/appsettings.Development.json b/samples/ASPNetCoreAuth/appsettings.Development.json new file mode 100644 index 0000000..ff66ba6 --- /dev/null +++ b/samples/ASPNetCoreAuth/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/samples/ASPNetCoreAuth/appsettings.json b/samples/ASPNetCoreAuth/appsettings.json new file mode 100644 index 0000000..005cc1d --- /dev/null +++ b/samples/ASPNetCoreAuth/appsettings.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "MiniJwt": { + "SecretKey": "sample-secret-key-at-least-32-bytes-long-for-hs256", + "Issuer": "ASPNetCoreAuthSample", + "Audience": "ASPNetCoreAuthClient", + "ExpirationMinutes": 60 + } +} diff --git a/samples/ConsoleMinimal/ConsoleMinimal.csproj b/samples/ConsoleMinimal/ConsoleMinimal.csproj new file mode 100644 index 0000000..a60fd1f --- /dev/null +++ b/samples/ConsoleMinimal/ConsoleMinimal.csproj @@ -0,0 +1,18 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + diff --git a/samples/ConsoleMinimal/Program.cs b/samples/ConsoleMinimal/Program.cs new file mode 100644 index 0000000..5733b74 --- /dev/null +++ b/samples/ConsoleMinimal/Program.cs @@ -0,0 +1,124 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using MiniJwt.Core.Attributes; +using MiniJwt.Core.Models; +using MiniJwt.Core.Services; +using System.IdentityModel.Tokens.Jwt; + +Console.WriteLine("=== MiniJwt.Core Console Sample ===\n"); + +// Configure JWT options +var options = new MiniJwtOptions +{ + SecretKey = "super-secret-key-at-least-32-bytes-long-for-hs256", + Issuer = "ConsoleApp", + Audience = "ConsoleClient", + ExpirationMinutes = 1 // 1 minute for demonstration +}; + +// Create a simple options monitor for console usage +var optionsMonitor = new SimpleOptionsMonitor(options); + +// Create the JWT service +var tokenHandler = new JwtSecurityTokenHandler { MapInboundClaims = false }; +var jwtService = new MiniJwtService( + optionsMonitor, + NullLogger.Instance, + tokenHandler +); + +// Define a payload model +var payload = new UserPayload +{ + UserId = "user123", + Email = "user@example.com", + Role = "admin" +}; + +// Generate a token +Console.WriteLine("1. Generating JWT token..."); +var token = jwtService.GenerateToken(payload); +if (token == null) +{ + Console.WriteLine(" ❌ Failed to generate token!"); + return; +} +Console.WriteLine($" ✅ Token generated: {token[..50]}...\n"); + +// Validate the token immediately +Console.WriteLine("2. Validating token..."); +var principal = jwtService.ValidateToken(token); +if (principal != null) +{ + Console.WriteLine(" ✅ Token is valid!"); + Console.WriteLine($" - Subject: {principal.FindFirst("sub")?.Value}"); + Console.WriteLine($" - Email: {principal.FindFirst("email")?.Value}"); + Console.WriteLine($" - Role: {principal.FindFirst("role")?.Value}\n"); +} +else +{ + Console.WriteLine(" ❌ Token validation failed!\n"); +} + +// Validate and deserialize +Console.WriteLine("3. Validating and deserializing token..."); +var deserializedUser = jwtService.ValidateAndDeserialize(token); +if (deserializedUser != null) +{ + Console.WriteLine(" ✅ Token deserialized successfully!"); + Console.WriteLine($" - UserId: {deserializedUser.UserId}"); + Console.WriteLine($" - Email: {deserializedUser.Email}"); + Console.WriteLine($" - Role: {deserializedUser.Role}\n"); +} +else +{ + Console.WriteLine(" ❌ Token deserialization failed!\n"); +} + +// Wait for token to expire +Console.WriteLine("4. Waiting for token to expire (65 seconds)..."); +await Task.Delay(TimeSpan.FromSeconds(65)); + +// Try to validate expired token +Console.WriteLine("\n5. Validating expired token..."); +var expiredPrincipal = jwtService.ValidateToken(token); +if (expiredPrincipal == null) +{ + Console.WriteLine(" ✅ Token correctly rejected as expired!\n"); +} +else +{ + Console.WriteLine(" ❌ Expired token was incorrectly accepted!\n"); +} + +Console.WriteLine("=== Sample completed ==="); + +// Payload model with MiniJwt attributes +public class UserPayload +{ + [MiniJwtClaim("sub")] + public string UserId { get; set; } = string.Empty; + + [MiniJwtClaim("email")] + public string Email { get; set; } = string.Empty; + + [MiniJwtClaim("role")] + public string Role { get; set; } = string.Empty; +} + +// Simple IOptionsMonitor implementation for console usage +public class SimpleOptionsMonitor : IOptionsMonitor +{ + private readonly T _currentValue; + + public SimpleOptionsMonitor(T currentValue) + { + _currentValue = currentValue; + } + + public T CurrentValue => _currentValue; + + public T Get(string? name) => _currentValue; + + public IDisposable? OnChange(Action listener) => null; +} diff --git a/samples/ConsoleMinimal/README.md b/samples/ConsoleMinimal/README.md new file mode 100644 index 0000000..f1253f2 --- /dev/null +++ b/samples/ConsoleMinimal/README.md @@ -0,0 +1,89 @@ +# ConsoleMinimal Sample + +This is a minimal console application demonstrating basic MiniJwt.Core functionality: +- Token generation with a custom payload +- Token validation +- Token deserialization back to an object +- Token expiration handling + +## Running the Sample + +```bash +cd samples/ConsoleMinimal +dotnet run +``` + +## What It Demonstrates + +1. **Configuration**: Manual setup of `MiniJwtOptions` without dependency injection +2. **Token Generation**: Creating a JWT with custom claims using the `[MiniJwtClaim]` attribute +3. **Token Validation**: Validating a token and accessing its claims via `ClaimsPrincipal` +4. **Deserialization**: Converting token claims back to a strongly-typed object +5. **Expiration**: Demonstrating that expired tokens are correctly rejected + +## Expected Output + +``` +=== MiniJwt.Core Console Sample === + +1. Generating JWT token... + ✅ Token generated: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... + +2. Validating token... + ✅ Token is valid! + - Subject: user123 + - Email: user@example.com + - Role: admin + +3. Validating and deserializing token... + ✅ Token deserialized successfully! + - UserId: user123 + - Email: user@example.com + - Role: admin + +4. Waiting for token to expire (65 seconds)... + +5. Validating expired token... + ✅ Token correctly rejected as expired! + +=== Sample completed === +``` + +## Key Concepts + +### Manual Service Creation + +Without dependency injection, you need to create the service manually: + +```csharp +var options = Options.Create(new MiniJwtOptions { ... }); +var tokenHandler = new JwtSecurityTokenHandler { MapInboundClaims = false }; +var jwtService = new MiniJwtService( + Options.CreateMonitor(options), + NullLogger.Instance, + tokenHandler +); +``` + +### Using Attributes for Claims + +Define your payload model with the `[MiniJwtClaim]` attribute: + +```csharp +public class UserPayload +{ + [MiniJwtClaim("sub")] + public string UserId { get; set; } + + [MiniJwtClaim("email")] + public string Email { get; set; } +} +``` + +This maps properties to JWT claim types. + +## Related Documentation + +- [Getting Started Guide](../../docs/getting-started.md) +- [Configuration Guide](../../docs/configuration.md) +- [More Examples](../../docs/examples.md) diff --git a/samples/WorkerService/Program.cs b/samples/WorkerService/Program.cs new file mode 100644 index 0000000..2706b5c --- /dev/null +++ b/samples/WorkerService/Program.cs @@ -0,0 +1,19 @@ +using MiniJwt.Core.Extensions; +using WorkerService; + +var builder = Host.CreateApplicationBuilder(args); + +// Register MiniJwt +builder.Services.AddMiniJwt(options => +{ + var config = builder.Configuration.GetSection("MiniJwt"); + options.SecretKey = config["SecretKey"] ?? throw new InvalidOperationException("SecretKey not configured"); + options.Issuer = config["Issuer"] ?? "WorkerServiceSample"; + options.Audience = config["Audience"] ?? "WorkerServiceClient"; + options.ExpirationMinutes = double.Parse(config["ExpirationMinutes"] ?? "5"); +}); + +builder.Services.AddHostedService(); + +var host = builder.Build(); +host.Run(); diff --git a/samples/WorkerService/Properties/launchSettings.json b/samples/WorkerService/Properties/launchSettings.json new file mode 100644 index 0000000..3c81bb6 --- /dev/null +++ b/samples/WorkerService/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "WorkerService": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + } + } +} diff --git a/samples/WorkerService/README.md b/samples/WorkerService/README.md new file mode 100644 index 0000000..ad6f79f --- /dev/null +++ b/samples/WorkerService/README.md @@ -0,0 +1,292 @@ +# WorkerService Sample + +This sample demonstrates using MiniJwt.Core in a .NET Worker Service (BackgroundService) for generating and validating JWT tokens in a long-running background process. + +## Features + +- Integration with .NET Worker Service / BackgroundService +- Dependency injection with `AddMiniJwt()` +- Periodic token generation in a background worker +- Token validation and deserialization +- Logging of token operations + +## Use Cases + +Worker Services with JWT tokens are useful for: +- Microservices that need to authenticate with other services +- Background jobs that call external APIs requiring JWT authentication +- Token generation for service-to-service communication +- Scheduled tasks that need secure API access + +## Running the Sample + +```bash +cd samples/WorkerService +dotnet run +``` + +The worker will: +1. Start and log initialization +2. Generate a JWT token every 10 seconds +3. Validate each generated token +4. Deserialize the token back to the payload object +5. Log all operations + +Press `Ctrl+C` to stop the worker. + +## Expected Output + +``` +info: WorkerService.Worker[0] + Worker started at: 12/18/2024 17:42:10 +00:00 +info: WorkerService.Worker[0] + Generating JWT token #0 for task a1b2c3d4-e5f6... +info: WorkerService.Worker[0] + Token generated successfully: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3b3JrZXJ... +info: WorkerService.Worker[0] + Token validated - WorkerId: worker-MACHINE123, TaskId: a1b2c3d4-e5f6... +info: WorkerService.Worker[0] + Token deserialized - Counter: 0, Timestamp: 2024-12-18T17:42:10.1234567Z +info: WorkerService.Worker[0] + Waiting 10 seconds before next token generation... + +info: WorkerService.Worker[0] + Generating JWT token #1 for task b2c3d4e5-f6a7... +... +``` + +## Configuration + +Configuration is in `appsettings.json`: + +```json +{ + "MiniJwt": { + "SecretKey": "worker-secret-key-at-least-32-bytes-long-for-hs256", + "Issuer": "WorkerServiceSample", + "Audience": "WorkerServiceClient", + "ExpirationMinutes": 5 + } +} +``` + +The token expiration is set to 5 minutes for this sample, but tokens are generated every 10 seconds so you can see fresh tokens being created. + +## Key Components + +### 1. Service Registration (Program.cs) + +```csharp +builder.Services.AddMiniJwt(options => +{ + var config = builder.Configuration.GetSection("MiniJwt"); + options.SecretKey = config["SecretKey"]; + options.Issuer = config["Issuer"]; + options.Audience = config["Audience"]; + options.ExpirationMinutes = double.Parse(config["ExpirationMinutes"] ?? "5"); +}); + +builder.Services.AddHostedService(); +``` + +### 2. Worker Implementation (Worker.cs) + +The worker: +- Injects `IMiniJwtService` through constructor +- Runs continuously in the background +- Generates tokens with custom payload every 10 seconds +- Validates and deserializes each token +- Logs all operations + +```csharp +public class Worker : BackgroundService +{ + private readonly IMiniJwtService _jwtService; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + var payload = new WorkerPayload { /* ... */ }; + var token = _jwtService.GenerateToken(payload); + var validated = _jwtService.ValidateToken(token); + + await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); + } + } +} +``` + +### 3. Custom Payload Model + +```csharp +public class WorkerPayload +{ + [MiniJwtClaim("worker_id")] + public string WorkerId { get; set; } + + [MiniJwtClaim("task_id")] + public string TaskId { get; set; } + + [MiniJwtClaim("timestamp")] + public string Timestamp { get; set; } + + [MiniJwtClaim("counter")] + public int Counter { get; set; } +} +``` + +## Real-World Scenarios + +### Scenario 1: API Client Worker + +A background worker that periodically calls an external API: + +```csharp +protected override async Task ExecuteAsync(CancellationToken stoppingToken) +{ + while (!stoppingToken.IsCancellationRequested) + { + // Generate token for authentication + var token = _jwtService.GenerateToken(new { service = "worker" }); + + // Call external API with token + using var client = new HttpClient(); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", token); + + var response = await client.GetAsync("https://api.example.com/data"); + + await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); + } +} +``` + +### Scenario 2: Service-to-Service Authentication + +Generate tokens for authenticating with other microservices: + +```csharp +public class ServiceAuthenticator +{ + private readonly IMiniJwtService _jwtService; + + public async Task GetServiceTokenAsync() + { + var payload = new + { + service = "order-processor", + permissions = new[] { "read:orders", "write:orders" } + }; + + return _jwtService.GenerateToken(payload) + ?? throw new InvalidOperationException("Token generation failed"); + } +} +``` + +### Scenario 3: Scheduled Token Rotation + +Automatically rotate tokens before they expire: + +```csharp +protected override async Task ExecuteAsync(CancellationToken stoppingToken) +{ + string currentToken = null; + var tokenLifetime = TimeSpan.FromMinutes(50); // Rotate before 60-min expiry + + while (!stoppingToken.IsCancellationRequested) + { + currentToken = _jwtService.GenerateToken(new { service = "background" }); + _logger.LogInformation("Token rotated"); + + // Store token in distributed cache or shared state + await _cache.SetAsync("service-token", currentToken); + + await Task.Delay(tokenLifetime, stoppingToken); + } +} +``` + +## Deployment Considerations + +### Running as Windows Service + +```bash +dotnet publish -c Release -r win-x64 --self-contained +sc create "MyWorkerService" binPath="C:\path\to\publish\WorkerService.exe" +sc start "MyWorkerService" +``` + +Note: The executable will be in the publish output directory and will match the project name. + +### Running as Linux Systemd Service + +Create `/etc/systemd/system/myworker.service`: + +```ini +[Unit] +Description=MiniJwt Worker Service +After=network.target + +[Service] +Type=notify +WorkingDirectory=/opt/myworker +ExecStart=/opt/myworker/WorkerService +Restart=always +User=myworkeruser + +[Install] +WantedBy=multi-user.target +``` + +Enable and start: +```bash +sudo systemctl enable myworker +sudo systemctl start myworker +sudo systemctl status myworker +``` + +### Docker Container + +```dockerfile +FROM mcr.microsoft.com/dotnet/runtime:8.0 +WORKDIR /app +COPY publish/ . +ENTRYPOINT ["dotnet", "WorkerService.dll"] +``` + +For the latest patch version, you can also use `8.0` which will automatically resolve to the latest 8.0.x version. + +## Monitoring and Health Checks + +Add health checks to monitor the worker: + +```csharp +builder.Services.AddHealthChecks() + .AddCheck("jwt-service"); + +public class JwtHealthCheck : IHealthCheck +{ + private readonly IMiniJwtService _jwtService; + + public Task CheckHealthAsync( + HealthCheckContext context, + CancellationToken cancellationToken = default) + { + var token = _jwtService.GenerateToken(new { test = "health" }); + var isHealthy = token != null && _jwtService.ValidateToken(token) != null; + + return Task.FromResult(isHealthy + ? HealthCheckResult.Healthy("JWT service is working") + : HealthCheckResult.Unhealthy("JWT service failed")); + } +} +``` + +## Related Documentation + +- [Getting Started Guide](../../docs/getting-started.md) +- [Configuration Guide](../../docs/configuration.md) +- [Examples](../../docs/examples.md) +- [FAQ](../../docs/faq.md) diff --git a/samples/WorkerService/Worker.cs b/samples/WorkerService/Worker.cs new file mode 100644 index 0000000..7afeff8 --- /dev/null +++ b/samples/WorkerService/Worker.cs @@ -0,0 +1,102 @@ +using MiniJwt.Core.Attributes; +using MiniJwt.Core.Services; + +namespace WorkerService; + +public class Worker : BackgroundService +{ + private readonly ILogger _logger; + private readonly IMiniJwtService _jwtService; + private int _tokenCount = 0; + + public Worker(ILogger logger, IMiniJwtService jwtService) + { + _logger = logger; + _jwtService = jwtService; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _logger.LogInformation("Worker started at: {time}", DateTimeOffset.Now); + + while (!stoppingToken.IsCancellationRequested) + { + try + { + // Generate a token with some sample data + var payload = new WorkerPayload + { + WorkerId = $"worker-{Environment.MachineName}", + TaskId = Guid.NewGuid().ToString(), + Timestamp = DateTime.UtcNow.ToString("O"), + Counter = Interlocked.Increment(ref _tokenCount) - 1 + }; + + _logger.LogInformation("Generating JWT token #{Counter} for task {TaskId}...", + payload.Counter, payload.TaskId); + + var token = _jwtService.GenerateToken(payload); + + if (token == null) + { + _logger.LogError("Failed to generate JWT token!"); + } + else + { + _logger.LogInformation("Token generated successfully: {Token}", + token.Length > 50 ? token[..50] + "..." : token); + + // Validate the token immediately + var principal = _jwtService.ValidateToken(token); + + if (principal != null) + { + var workerId = principal.FindFirst("worker_id")?.Value; + var taskId = principal.FindFirst("task_id")?.Value; + _logger.LogInformation("Token validated - WorkerId: {WorkerId}, TaskId: {TaskId}", + workerId, taskId); + + // Deserialize back to object + var deserialized = _jwtService.ValidateAndDeserialize(token); + if (deserialized != null) + { + _logger.LogInformation("Token deserialized - Counter: {Counter}, Timestamp: {Timestamp}", + deserialized.Counter, deserialized.Timestamp); + } + } + else + { + _logger.LogWarning("Token validation failed!"); + } + } + + // Wait 10 seconds before generating next token + _logger.LogInformation("Waiting 10 seconds before next token generation...\n"); + await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error in worker execution"); + await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); + } + } + + _logger.LogInformation("Worker stopped at: {time}", DateTimeOffset.Now); + } +} + +// Payload model for worker tokens +public class WorkerPayload +{ + [MiniJwtClaim("worker_id")] + public string WorkerId { get; set; } = string.Empty; + + [MiniJwtClaim("task_id")] + public string TaskId { get; set; } = string.Empty; + + [MiniJwtClaim("timestamp")] + public string Timestamp { get; set; } = string.Empty; + + [MiniJwtClaim("counter")] + public int Counter { get; set; } +} diff --git a/samples/WorkerService/WorkerService.csproj b/samples/WorkerService/WorkerService.csproj new file mode 100644 index 0000000..4aaee6b --- /dev/null +++ b/samples/WorkerService/WorkerService.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + dotnet-WorkerService-72e4906a-e203-476d-b091-2e2358cbbdb7 + + + + + + + + + + diff --git a/samples/WorkerService/appsettings.Development.json b/samples/WorkerService/appsettings.Development.json new file mode 100644 index 0000000..6901764 --- /dev/null +++ b/samples/WorkerService/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/samples/WorkerService/appsettings.json b/samples/WorkerService/appsettings.json new file mode 100644 index 0000000..ef9770a --- /dev/null +++ b/samples/WorkerService/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "MiniJwt": { + "SecretKey": "worker-secret-key-at-least-32-bytes-long-for-hs256", + "Issuer": "WorkerServiceSample", + "Audience": "WorkerServiceClient", + "ExpirationMinutes": 5 + } +} diff --git a/src/MiniJwt.Core/MiniJwt.Core.csproj b/src/MiniJwt.Core/MiniJwt.Core.csproj index 651a320..c2cbe40 100644 --- a/src/MiniJwt.Core/MiniJwt.Core.csproj +++ b/src/MiniJwt.Core/MiniJwt.Core.csproj @@ -4,7 +4,7 @@ net6.0;net7.0;net8.0;net9.0;net10.0 true MiniJwt.Core - 1.1.1 + 1.2.0 jeanlrnt enable enable @@ -12,6 +12,7 @@ jwt;auth;security;minimal-api https://github.com/jeanlrnt/MiniJwt.Core README.md + true @@ -21,6 +22,11 @@ + + + + + diff --git a/src/MiniJwt.Core/Services/MiniJwtService.cs b/src/MiniJwt.Core/Services/MiniJwtService.cs index a51c370..8eda5bf 100644 --- a/src/MiniJwt.Core/Services/MiniJwtService.cs +++ b/src/MiniJwt.Core/Services/MiniJwtService.cs @@ -8,6 +8,7 @@ using System.Globalization; using Microsoft.Extensions.Logging; using MiniJwt.Core.Models; +using System.Collections.Concurrent; namespace MiniJwt.Core.Services; @@ -15,6 +16,7 @@ public class MiniJwtService : IMiniJwtService, IDisposable { private readonly ILogger _logger; private readonly JwtSecurityTokenHandler _tokenHandler; + private readonly TimeProvider _timeProvider; private readonly IDisposable? _optionsChangeRegistration; private readonly object _sync = new object(); @@ -25,10 +27,31 @@ public class MiniJwtService : IMiniJwtService, IDisposable private const int MinimumKeyLengthBytes = 32; // 256 bits for HS256 + // Reflection cache: stores property metadata for each type to avoid repeated reflection operations + private static readonly ConcurrentDictionary _reflectionCache = new(); + + private sealed class PropertyClaimInfo + { + public PropertyInfo Property { get; } + public string ClaimType { get; } + + public PropertyClaimInfo(PropertyInfo property, string claimType) + { + Property = property; + ClaimType = claimType; + } + } + public MiniJwtService(IOptionsMonitor optionsMonitor, ILogger logger, JwtSecurityTokenHandler tokenHandler) + : this(optionsMonitor, logger, tokenHandler, TimeProvider.System) + { + } + + public MiniJwtService(IOptionsMonitor optionsMonitor, ILogger logger, JwtSecurityTokenHandler tokenHandler, TimeProvider timeProvider) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _tokenHandler = tokenHandler ?? throw new ArgumentNullException(nameof(tokenHandler)); + _timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider)); _options = optionsMonitor.CurrentValue ?? throw new ArgumentNullException(nameof(optionsMonitor)); RefreshFromOptions(_options); @@ -78,6 +101,26 @@ private void RefreshFromOptions(MiniJwtOptions opts) }; } + private static PropertyClaimInfo[] GetOrComputePropertyClaimInfos(Type type) + { + return _reflectionCache.GetOrAdd(type, t => + { + var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public); + var claimInfos = new List(props.Length); + + foreach (var prop in props) + { + var attr = prop.GetCustomAttribute(); + if (attr is not null) + { + claimInfos.Add(new PropertyClaimInfo(prop, attr.ClaimType)); + } + } + + return claimInfos.ToArray(); + }); + } + /// public string? GenerateToken(T payload) { @@ -95,21 +138,19 @@ private void RefreshFromOptions(MiniJwtOptions opts) return null; } - var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); - var claims = new List(props.Length + 1); + var propertyClaimInfos = GetOrComputePropertyClaimInfos(typeof(T)); + var claims = new List(propertyClaimInfos.Length + 1); - foreach (var prop in props) + foreach (var info in propertyClaimInfos) { - var attr = prop.GetCustomAttribute(); - if (attr is null) continue; - var raw = prop.GetValue(payload); + var raw = info.Property.GetValue(payload); if (raw is null) continue; - claims.Add(new Claim(attr.ClaimType, raw.ToString() ?? string.Empty)); + claims.Add(new Claim(info.ClaimType, raw.ToString() ?? string.Empty)); } claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); - var now = DateTime.UtcNow; + var now = _timeProvider.GetUtcNow().UtcDateTime; var expires = now.AddMinutes(currentOptions.ExpirationMinutes); var jwt = new JwtSecurityToken( @@ -184,15 +225,13 @@ private void RefreshFromOptions(MiniJwtOptions opts) if (principal == null) return default; var result = new T(); - var props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public); + var propertyClaimInfos = GetOrComputePropertyClaimInfos(typeof(T)); - foreach (var prop in props) + foreach (var info in propertyClaimInfos) { - var attr = prop.GetCustomAttribute(); - if (attr == null) continue; - var claim = principal.Claims.FirstOrDefault(c => c.Type == attr.ClaimType); + var claim = principal.Claims.FirstOrDefault(c => c.Type == info.ClaimType); if (claim == null) continue; - TrySetProperty(result, prop, claim.Value); + TrySetProperty(result, info.Property, claim.Value); } return result; diff --git a/src/MiniJwt.Tests/MiniJwt.Tests.csproj b/src/MiniJwt.Tests/MiniJwt.Tests.csproj index 426e6aa..e8a2726 100644 --- a/src/MiniJwt.Tests/MiniJwt.Tests.csproj +++ b/src/MiniJwt.Tests/MiniJwt.Tests.csproj @@ -9,6 +9,7 @@ + diff --git a/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs b/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs new file mode 100644 index 0000000..0e1754e --- /dev/null +++ b/src/MiniJwt.Tests/MiniJwtTests.ReflectionCache.cs @@ -0,0 +1,77 @@ +using System; +using System.Linq; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using MiniJwt.Core.Attributes; +using MiniJwt.Core.Models; +using MiniJwt.Core.Services; +using Xunit; + +namespace MiniJwt.Tests; + +public partial class MiniJwtTests +{ + private class CacheTestPayload + { + [MiniJwtClaim("test_id")] + public int Id { get; set; } + + [MiniJwtClaim("test_name")] + public string? Name { get; set; } + } + + [Fact] + public void ReflectionCache_ShouldReuseMetadata_AcrossMultipleGenerateTokenCalls() + { + // Arrange + var svc = CreateService(); + var payload1 = new CacheTestPayload { Id = 1, Name = "First" }; + var payload2 = new CacheTestPayload { Id = 2, Name = "Second" }; + + // Act - Generate multiple tokens with the same type + var token1 = svc.GenerateToken(payload1); + var token2 = svc.GenerateToken(payload2); + + // Assert - Both tokens should be generated successfully + Assert.NotNull(token1); + Assert.NotNull(token2); + + // Validate that both tokens deserialize correctly (proving cache is working) + var deserialized1 = svc.ValidateAndDeserialize(token1); + var deserialized2 = svc.ValidateAndDeserialize(token2); + + Assert.NotNull(deserialized1); + Assert.NotNull(deserialized2); + Assert.Equal(payload1.Id, deserialized1.Id); + Assert.Equal(payload1.Name, deserialized1.Name); + Assert.Equal(payload2.Id, deserialized2.Id); + Assert.Equal(payload2.Name, deserialized2.Name); + } + + [Fact] + public void ReflectionCache_ShouldWorkWithDifferentTypes() + { + // Arrange + var svc = CreateService(); + var testUser = new TestUser { Id = 1, Email = "test@test.com", Name = "User" }; + var cachePayload = new CacheTestPayload { Id = 2, Name = "Payload" }; + + // Act - Generate tokens for different types + var userToken = svc.GenerateToken(testUser); + var payloadToken = svc.GenerateToken(cachePayload); + + // Assert - Both should work correctly + Assert.NotNull(userToken); + Assert.NotNull(payloadToken); + + var deserializedUser = svc.ValidateAndDeserialize(userToken); + var deserializedPayload = svc.ValidateAndDeserialize(payloadToken); + + Assert.NotNull(deserializedUser); + Assert.NotNull(deserializedPayload); + Assert.Equal(testUser.Id, deserializedUser.Id); + Assert.Equal(testUser.Email, deserializedUser.Email); + Assert.Equal(cachePayload.Id, deserializedPayload.Id); + Assert.Equal(cachePayload.Name, deserializedPayload.Name); + } +} diff --git a/src/MiniJwt.Tests/MiniJwtTests.Service.cs b/src/MiniJwt.Tests/MiniJwtTests.Service.cs index afb8eed..1b139e9 100644 --- a/src/MiniJwt.Tests/MiniJwtTests.Service.cs +++ b/src/MiniJwt.Tests/MiniJwtTests.Service.cs @@ -2,6 +2,7 @@ using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; using MiniJwt.Core.Attributes; using MiniJwt.Core.Models; using MiniJwt.Core.Services; @@ -285,4 +286,97 @@ public void Dispose_ShouldCleanupOptionsChangeSubscription() // Assert Assert.True(trackableDisposable.IsDisposed, "The options change subscription should be disposed when the service is disposed"); } + + [Fact] + public void GenerateToken_WithFakeTimeProvider_ShouldUseProvidedTime() + { + // Arrange + var fakeTimeProvider = new FakeTimeProvider(); + var fixedTime = new DateTimeOffset(2024, 1, 15, 10, 30, 0, TimeSpan.Zero); + fakeTimeProvider.SetUtcNow(fixedTime); + + var options = new SimpleOptionsMonitor(new MiniJwtOptions + { + SecretKey = "IntegrationTestSecretKey_LongEnough_For_HS256_0123456789", + Issuer = "MiniJwt.Tests", + Audience = "MiniJwt.Tests.Client", + ExpirationMinutes = 60 + }); + + using var loggerFactory = new LoggerFactory(); + var service = new MiniJwtService( + options, + loggerFactory.CreateLogger(), + new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(), + fakeTimeProvider + ); + + var user = new TestUser { Id = 1, Email = "test@test.com", Name = "User Test" }; + + // Act + var token = service.GenerateToken(user); + + // Assert + Assert.NotNull(token); + + // Decode the token to verify it uses the fake time + var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); + var jwtToken = handler.ReadJwtToken(token); + + // The token's NotBefore should match the fixed time + Assert.Equal(fixedTime.UtcDateTime, jwtToken.ValidFrom); + + // The token's expiration should be 60 minutes after the fixed time + var expectedExpiry = fixedTime.AddMinutes(60).UtcDateTime; + Assert.Equal(expectedExpiry, jwtToken.ValidTo); + } + + [Fact] + public void GenerateToken_WithAdvancedTime_UsesUpdatedTime() + { + // Arrange + var fakeTimeProvider = new FakeTimeProvider(); + var initialTime = new DateTimeOffset(2024, 1, 15, 10, 0, 0, TimeSpan.Zero); + fakeTimeProvider.SetUtcNow(initialTime); + + var options = new SimpleOptionsMonitor(new MiniJwtOptions + { + SecretKey = "IntegrationTestSecretKey_LongEnough_For_HS256_0123456789", + Issuer = "MiniJwt.Tests", + Audience = "MiniJwt.Tests.Client", + ExpirationMinutes = 10 // 10 minutes + }); + + using var loggerFactory = new LoggerFactory(); + var service = new MiniJwtService( + options, + loggerFactory.CreateLogger(), + new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(), + fakeTimeProvider + ); + + var user = new TestUser { Id = 1, Email = "test@test.com", Name = "User Test" }; + + // Generate token at initial time + var token = service.GenerateToken(user); + Assert.NotNull(token); + + // Verify the token was generated with the fake time + var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); + var jwtToken = handler.ReadJwtToken(token); + Assert.Equal(initialTime.UtcDateTime, jwtToken.ValidFrom); + Assert.Equal(initialTime.AddMinutes(10).UtcDateTime, jwtToken.ValidTo); + + // Advance the fake time by 5 minutes + fakeTimeProvider.Advance(TimeSpan.FromMinutes(5)); + + // Generate another token - it should use the new advanced time + var token2 = service.GenerateToken(user); + Assert.NotNull(token2); + + var jwtToken2 = handler.ReadJwtToken(token2); + var expectedTime = initialTime.AddMinutes(5).UtcDateTime; + Assert.Equal(expectedTime, jwtToken2.ValidFrom); + Assert.Equal(expectedTime.AddMinutes(10), jwtToken2.ValidTo); + } } \ No newline at end of file