using System.Security.Claims; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Options; namespace Flypaper.Web.Mcp; public sealed class McpTokenAuthenticationHandler( IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, McpTokenService tokens) : AuthenticationHandler(options, logger, encoder) { public const string SchemeName = "McpToken"; protected override async Task HandleAuthenticateAsync() { var header = Request.Headers.Authorization.ToString(); if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { return AuthenticateResult.NoResult(); } if (!await tokens.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted)) { return AuthenticateResult.Fail("Invalid MCP token."); } var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName); return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName)); } protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { Response.StatusCode = StatusCodes.Status401Unauthorized; Response.Headers.WWWAuthenticate = "Bearer"; await Response.WriteAsJsonAsync(new { error = "invalid_token" }); } }