|
| 1 | +using Microsoft.AspNetCore.Authentication; |
| 2 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 3 | +using Microsoft.IdentityModel.Tokens; |
| 4 | + |
| 5 | +namespace OpenDeepWiki.MCP; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Configures MCP server authentication using Google as the OAuth 2.1 authorization server. |
| 9 | +/// Implements Protected Resource Metadata (RFC 9728) for MCP client discovery. |
| 10 | +/// </summary> |
| 11 | +public static class McpAuthConfiguration |
| 12 | +{ |
| 13 | + public const string McpGoogleScheme = "McpGoogle"; |
| 14 | + public const string McpPolicyName = "McpAccess"; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Adds Google OAuth token validation as a secondary authentication scheme for MCP. |
| 18 | + /// </summary> |
| 19 | + public static AuthenticationBuilder AddMcpGoogleAuth( |
| 20 | + this AuthenticationBuilder builder, |
| 21 | + IConfiguration configuration) |
| 22 | + { |
| 23 | + var googleClientId = configuration["GOOGLE_CLIENT_ID"] |
| 24 | + ?? configuration["Google:ClientId"] |
| 25 | + ?? throw new InvalidOperationException( |
| 26 | + "GOOGLE_CLIENT_ID is required for MCP OAuth authentication"); |
| 27 | + |
| 28 | + builder.AddJwtBearer(McpGoogleScheme, options => |
| 29 | + { |
| 30 | + options.Authority = "https://accounts.google.com"; |
| 31 | + options.TokenValidationParameters = new TokenValidationParameters |
| 32 | + { |
| 33 | + ValidateIssuer = true, |
| 34 | + ValidIssuers = new[] |
| 35 | + { |
| 36 | + "https://accounts.google.com", |
| 37 | + "accounts.google.com" |
| 38 | + }, |
| 39 | + ValidateAudience = true, |
| 40 | + ValidAudience = googleClientId, |
| 41 | + ValidateLifetime = true, |
| 42 | + ValidateIssuerSigningKey = true, |
| 43 | + NameClaimType = "name", |
| 44 | + RoleClaimType = "roles" |
| 45 | + }; |
| 46 | + |
| 47 | + options.Events = new JwtBearerEvents |
| 48 | + { |
| 49 | + OnAuthenticationFailed = context => |
| 50 | + { |
| 51 | + var logger = context.HttpContext.RequestServices |
| 52 | + .GetRequiredService<ILoggerFactory>() |
| 53 | + .CreateLogger("OpenDeepWiki.MCP.McpAuthConfiguration"); |
| 54 | + logger.LogDebug("MCP Google auth failed: {Error}", context.Exception.Message); |
| 55 | + return Task.CompletedTask; |
| 56 | + } |
| 57 | + }; |
| 58 | + }); |
| 59 | + |
| 60 | + return builder; |
| 61 | + } |
| 62 | + |
| 63 | + /// <summary> |
| 64 | + /// Maps the Protected Resource Metadata endpoint (RFC 9728). |
| 65 | + /// Claude and other MCP clients fetch this to discover the authorization server. |
| 66 | + /// Mapped at both /.well-known/ (standard) and /api/.well-known/ (for reverse proxy setups). |
| 67 | + /// </summary> |
| 68 | + public static WebApplication MapProtectedResourceMetadata( |
| 69 | + this WebApplication app) |
| 70 | + { |
| 71 | + app.MapGet("/.well-known/oauth-protected-resource", HandleProtectedResourceMetadata) |
| 72 | + .AllowAnonymous(); |
| 73 | + app.MapGet("/api/.well-known/oauth-protected-resource", HandleProtectedResourceMetadata) |
| 74 | + .AllowAnonymous(); |
| 75 | + |
| 76 | + return app; |
| 77 | + } |
| 78 | + |
| 79 | + private static IResult HandleProtectedResourceMetadata(HttpContext context) |
| 80 | + { |
| 81 | + var config = context.RequestServices.GetRequiredService<IConfiguration>(); |
| 82 | + // Derive public base URL from CORS origins or forwarded headers |
| 83 | + var baseUrl = config["ASPNETCORE_CORS_ORIGINS"]?.TrimEnd('/'); |
| 84 | + if (string.IsNullOrEmpty(baseUrl)) |
| 85 | + { |
| 86 | + var request = context.Request; |
| 87 | + var scheme = request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? request.Scheme; |
| 88 | + var host = request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? request.Host.ToString(); |
| 89 | + baseUrl = $"{scheme}://{host}"; |
| 90 | + } |
| 91 | + |
| 92 | + var metadata = new |
| 93 | + { |
| 94 | + resource = $"{baseUrl}/api/mcp", |
| 95 | + authorization_servers = new[] { baseUrl }, |
| 96 | + scopes_supported = new[] { "openid", "email", "profile" }, |
| 97 | + resource_documentation = $"{baseUrl}/docs/mcp" |
| 98 | + }; |
| 99 | + |
| 100 | + return Results.Json(metadata); |
| 101 | + } |
| 102 | +} |
0 commit comments