|
| 1 | +using System.IdentityModel.Tokens.Jwt; |
| 2 | +using System.Security.Claims; |
| 3 | +using Microsoft.AspNetCore.Http; |
| 4 | +using Microsoft.Extensions.Configuration; |
| 5 | +using Microsoft.IdentityModel.Tokens; |
| 6 | + |
| 7 | +namespace Genocs.Auth; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Middleware for handling JWT authentication and API key authentication. |
| 11 | +/// </summary> |
| 12 | +/// <remarks> |
| 13 | +/// This middleware supports dual authentication modes: |
| 14 | +/// 1. API Key authentication via x-gnx-apikey header for system-to-system communication |
| 15 | +/// 2. JWT Bearer token authentication for user authentication |
| 16 | +/// When API key is provided, it bypasses JWT validation and sets up API key-based claims. |
| 17 | +/// </remarks> |
| 18 | +public class JWTOrApiKeyAuthenticationMiddleware(RequestDelegate next, IConfiguration configuration) |
| 19 | +{ |
| 20 | + private readonly RequestDelegate _next = next; |
| 21 | + private readonly IConfiguration _configuration = configuration; |
| 22 | + |
| 23 | + public async Task Invoke(HttpContext context) |
| 24 | + { |
| 25 | + // Check for API key authentication first |
| 26 | + string? apiKey = context.Request.Headers["x-gnx-apikey"]; |
| 27 | + if (!string.IsNullOrEmpty(apiKey)) |
| 28 | + { |
| 29 | + if (await ValidateApiKeyAsync(apiKey)) |
| 30 | + { |
| 31 | + // Set up API key-based authentication |
| 32 | + var claims = new[] |
| 33 | + { |
| 34 | + new Claim(ClaimTypes.NameIdentifier, "api-client"), |
| 35 | + new Claim(ClaimTypes.Name, "API Client"), |
| 36 | + new Claim("auth_type", "apikey"), |
| 37 | + new Claim("api_key", apiKey) |
| 38 | + }; |
| 39 | + |
| 40 | + var identity = new ClaimsIdentity(claims, "ApiKey"); |
| 41 | + context.User = new ClaimsPrincipal(identity); |
| 42 | + |
| 43 | + await _next(context); |
| 44 | + return; |
| 45 | + } |
| 46 | + else |
| 47 | + { |
| 48 | + // Invalid API key |
| 49 | + context.Response.StatusCode = 401; |
| 50 | + await context.Response.WriteAsync("Invalid API key"); |
| 51 | + return; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // Check for Firebase JWT authentication |
| 56 | + string? authHeader = context.Request.Headers.Authorization; |
| 57 | + if (authHeader?.StartsWith("Bearer ") == true) |
| 58 | + { |
| 59 | + string token = authHeader["Bearer ".Length..].Trim(); |
| 60 | + |
| 61 | + try |
| 62 | + { |
| 63 | + var handler = new JwtSecurityTokenHandler(); |
| 64 | + var jsonToken = handler.ReadToken(token) as JwtSecurityToken ?? throw new SecurityTokenException("Invalid token format"); |
| 65 | + var payload = jsonToken.Payload; |
| 66 | + var claims = new[] |
| 67 | + { |
| 68 | + new Claim(ClaimTypes.NameIdentifier, payload["user_id"]?.ToString() ?? string.Empty), |
| 69 | + new Claim(ClaimTypes.Name, payload["name"]?.ToString() ?? string.Empty), |
| 70 | + new Claim("auth_type", "jwt") |
| 71 | + |
| 72 | + // Add more claims as needed |
| 73 | + }; |
| 74 | + |
| 75 | + var identity = new ClaimsIdentity(claims, "AuthenticationTypes.Federation"); |
| 76 | + context.User = new ClaimsPrincipal(identity); |
| 77 | + } |
| 78 | + catch (Exception) |
| 79 | + { |
| 80 | + // Token validation failed - but don't return error here |
| 81 | + // Let the authorization attributes handle it |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + await _next(context); |
| 86 | + } |
| 87 | + |
| 88 | + /// <summary> |
| 89 | + /// Validates the provided API key against configured valid keys. |
| 90 | + /// </summary> |
| 91 | + /// <param name="apiKey">The API key to validate.</param> |
| 92 | + /// <returns>True if the API key is valid, false otherwise.</returns> |
| 93 | + private async Task<bool> ValidateApiKeyAsync(string apiKey) |
| 94 | + { |
| 95 | + // Get valid API keys from configuration |
| 96 | + string[] validApiKeys = _configuration.GetSection("Authentication:ApiKeys").Get<string[]>() ?? []; |
| 97 | + |
| 98 | + // For development/testing |
| 99 | + string? devApiKey = _configuration["Authentication:DevApiKey"]; |
| 100 | + |
| 101 | + bool isOk = validApiKeys.Contains(apiKey) || (!string.IsNullOrWhiteSpace(devApiKey) && devApiKey == apiKey); |
| 102 | + |
| 103 | + return await Task.FromResult(isOk); |
| 104 | + } |
| 105 | +} |
0 commit comments