|
| 1 | +using System.Security.Claims; |
| 2 | +using System.Security.Cryptography; |
| 3 | +using System.Text; |
| 4 | +using System.Text.Encodings.Web; |
| 5 | +using Microsoft.AspNetCore.Authentication; |
| 6 | +using Microsoft.EntityFrameworkCore; |
| 7 | +using Microsoft.Extensions.Options; |
| 8 | +using OpenDeepWiki.EFCore; |
| 9 | + |
| 10 | +namespace OpenDeepWiki.MCP; |
| 11 | + |
| 12 | +public class ApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> |
| 13 | +{ |
| 14 | + private const string ApiKeyPrefix = "dwk_"; |
| 15 | + private readonly IServiceScopeFactory _scopeFactory; |
| 16 | + |
| 17 | + public ApiKeyAuthenticationHandler( |
| 18 | + IOptionsMonitor<AuthenticationSchemeOptions> options, |
| 19 | + ILoggerFactory logger, |
| 20 | + UrlEncoder encoder, |
| 21 | + IServiceScopeFactory scopeFactory) |
| 22 | + : base(options, logger, encoder) |
| 23 | + { |
| 24 | + _scopeFactory = scopeFactory; |
| 25 | + } |
| 26 | + |
| 27 | + protected override async Task<AuthenticateResult> HandleAuthenticateAsync() |
| 28 | + { |
| 29 | + var authHeader = Request.Headers.Authorization.ToString(); |
| 30 | + if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) |
| 31 | + return AuthenticateResult.NoResult(); |
| 32 | + |
| 33 | + var token = authHeader["Bearer ".Length..].Trim(); |
| 34 | + if (!token.StartsWith(ApiKeyPrefix)) |
| 35 | + return AuthenticateResult.NoResult(); |
| 36 | + |
| 37 | + // Extract prefix and compute hash |
| 38 | + var randomPart = token[ApiKeyPrefix.Length..]; |
| 39 | + if (randomPart.Length < 8) |
| 40 | + return AuthenticateResult.Fail("Invalid API key format"); |
| 41 | + |
| 42 | + var keyPrefix = randomPart[..8]; |
| 43 | + var tokenBytes = Encoding.UTF8.GetBytes(token); |
| 44 | + var hashBytes = SHA256.HashData(tokenBytes); |
| 45 | + var keyHash = Convert.ToHexString(hashBytes).ToLowerInvariant(); |
| 46 | + |
| 47 | + // Look up in database using a new scope (handler is singleton-like) |
| 48 | + using var scope = _scopeFactory.CreateScope(); |
| 49 | + var context = scope.ServiceProvider.GetRequiredService<IContext>(); |
| 50 | + |
| 51 | + var apiKey = await context.ApiKeys |
| 52 | + .Include(k => k.User) |
| 53 | + .FirstOrDefaultAsync(k => k.KeyPrefix == keyPrefix && !k.IsDeleted); |
| 54 | + |
| 55 | + if (apiKey == null) |
| 56 | + return AuthenticateResult.Fail("Invalid API key"); |
| 57 | + |
| 58 | + // Constant-time hash comparison |
| 59 | + var storedHashBytes = Convert.FromHexString(apiKey.KeyHash); |
| 60 | + if (!CryptographicOperations.FixedTimeEquals(hashBytes, storedHashBytes)) |
| 61 | + return AuthenticateResult.Fail("Invalid API key"); |
| 62 | + |
| 63 | + // Check expiration |
| 64 | + if (apiKey.ExpiresAt.HasValue && apiKey.ExpiresAt.Value < DateTime.UtcNow) |
| 65 | + return AuthenticateResult.Fail("API key has expired"); |
| 66 | + |
| 67 | + // Check user exists and is not deleted |
| 68 | + if (apiKey.User == null || apiKey.User.IsDeleted) |
| 69 | + return AuthenticateResult.Fail("Associated user not found or disabled"); |
| 70 | + |
| 71 | + // Load user roles |
| 72 | + var userRoles = await context.UserRoles |
| 73 | + .Where(ur => ur.UserId == apiKey.UserId) |
| 74 | + .Join(context.Roles.Where(r => !r.IsDeleted), |
| 75 | + ur => ur.RoleId, r => r.Id, |
| 76 | + (ur, r) => r.Name) |
| 77 | + .ToListAsync(); |
| 78 | + |
| 79 | + // Build claims (same as JwtService) |
| 80 | + var claims = new List<Claim> |
| 81 | + { |
| 82 | + new(ClaimTypes.NameIdentifier, apiKey.UserId), |
| 83 | + new(ClaimTypes.Name, apiKey.User.Name ?? string.Empty), |
| 84 | + new(ClaimTypes.Email, apiKey.User.Email ?? string.Empty), |
| 85 | + }; |
| 86 | + foreach (var role in userRoles) |
| 87 | + { |
| 88 | + claims.Add(new Claim(ClaimTypes.Role, role)); |
| 89 | + } |
| 90 | + |
| 91 | + var identity = new ClaimsIdentity(claims, Scheme.Name); |
| 92 | + var principal = new ClaimsPrincipal(identity); |
| 93 | + var ticket = new AuthenticationTicket(principal, Scheme.Name); |
| 94 | + |
| 95 | + // Capture values before fire-and-forget (HttpContext may be recycled after response completes) |
| 96 | + var apiKeyId = apiKey.Id; |
| 97 | + var remoteIp = Request.HttpContext.Connection.RemoteIpAddress?.ToString(); |
| 98 | + |
| 99 | + // Update last used info (fire and forget) |
| 100 | + _ = Task.Run(async () => |
| 101 | + { |
| 102 | + try |
| 103 | + { |
| 104 | + using var updateScope = _scopeFactory.CreateScope(); |
| 105 | + var updateContext = updateScope.ServiceProvider.GetRequiredService<IContext>(); |
| 106 | + var keyToUpdate = await updateContext.ApiKeys.FindAsync(apiKeyId); |
| 107 | + if (keyToUpdate != null) |
| 108 | + { |
| 109 | + keyToUpdate.LastUsedAt = DateTime.UtcNow; |
| 110 | + keyToUpdate.LastUsedIp = remoteIp; |
| 111 | + await updateContext.SaveChangesAsync(); |
| 112 | + } |
| 113 | + } |
| 114 | + catch (Exception ex) |
| 115 | + { |
| 116 | + Logger.LogWarning(ex, "Failed to update API key last used info for prefix {KeyPrefix}", keyPrefix); |
| 117 | + } |
| 118 | + }); |
| 119 | + |
| 120 | + Logger.LogInformation("API key authenticated: prefix={KeyPrefix}, user={Email}", keyPrefix, apiKey.User.Email); |
| 121 | + return AuthenticateResult.Success(ticket); |
| 122 | + } |
| 123 | +} |
0 commit comments