diff --git a/.template.config/template.json b/.template.config/template.json index 5c8f178..f552880 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -25,6 +25,60 @@ "displayName": "The name of the author of the solution.", "defaultValue": "Stephen Walsh", "replaces": "Stephen Walsh" + }, + "authority": { + "type": "parameter", + "datatype": "string", + "displayName": "The OAuth authorization server that issues access tokens. Leave empty to run the MCP endpoint without authentication.", + "defaultValue": "" + }, + "audience": { + "type": "parameter", + "datatype": "string", + "displayName": "The audience access tokens must be issued for, usually the server's own URL.", + "defaultValue": "" + }, + "authorityValue": { + "type": "generated", + "generator": "join", + "replaces": "\"Authority\": \"\"", + "parameters": { + "symbols": [ + { + "type": "const", + "value": "\"Authority\": \"" + }, + { + "type": "ref", + "value": "authority" + }, + { + "type": "const", + "value": "\"" + } + ] + } + }, + "audienceValue": { + "type": "generated", + "generator": "join", + "replaces": "\"Audience\": \"\"", + "parameters": { + "symbols": [ + { + "type": "const", + "value": "\"Audience\": \"" + }, + { + "type": "ref", + "value": "audience" + }, + { + "type": "const", + "value": "\"" + } + ] + } } } } diff --git a/README.md b/README.md index 78c7383..9434071 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,16 @@ dotnet new install CleanModelContextProtocol.Template dotnet new cleanmodelcontextprotocol --name {YOUR_SOLUTION_NAMESPACE} --authorName "{YOUR_NAME}" ``` +### Protect the server with OAuth (optional) + +The server runs without authentication unless you give it an authorization server. Pass one when you create the solution, or set `Authentication:Authority` and `Authentication:Audience` in `appsettings.json` later. + +``` bash +dotnet new cleanmodelcontextprotocol --name {YOUR_SOLUTION_NAMESPACE} --authority https://{YOUR_AUTHORIZATION_SERVER} --audience https://{YOUR_SERVER_URL} +``` + +With an authority set, `/mcp` needs a bearer token issued for the audience, and the server publishes [protected resource metadata](https://modelcontextprotocol.io/specification/latest/basic/authorization) at `/.well-known/oauth-protected-resource/mcp` so MCP clients can find the authorization server and sign in. List the scopes clients should ask for in `Authentication:Scopes`. + ## Running the project ``` bash @@ -78,6 +88,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec - Resources for each movie, author and review (`movies://{movieId}`, `authors://{authorId}`, `reviews://{reviewId}`) and the server version (`server://version`) - Prompts for common jobs (`summarise_movie_reception`, `compare_movies`, `review_movie`) that embed the movies they're about, with completions that suggest movie titles and author names as you type - Search with paging and small results by default: every list returns 10 items, a total count and a cursor, with names and average ratings next to ids +- Optional OAuth protection for `/mcp`: JWT bearer tokens plus MCP protected resource metadata, turned on by setting an authority - Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker - Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator) - Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation) in an Application pipeline behaviour diff --git a/src/Presentation/Authentication/AuthenticationSettings.cs b/src/Presentation/Authentication/AuthenticationSettings.cs new file mode 100644 index 0000000..e3eecd7 --- /dev/null +++ b/src/Presentation/Authentication/AuthenticationSettings.cs @@ -0,0 +1,27 @@ +namespace CleanModelContextProtocol.Presentation.Authentication; + +using Microsoft.Extensions.Configuration; + +/// +/// OAuth settings for protecting the MCP endpoint. Leave the authority empty to run the server without authentication. +/// +public class AuthenticationSettings +{ + public const string SectionName = "Authentication"; + + /// The OAuth authorization server that issues access tokens, such as https://login.example.com. + public string Authority { get; init; } + + /// The audience access tokens must be issued for. This is usually the server's own URL. + public string Audience { get; init; } + + /// The scopes clients should ask for, published in the protected resource metadata. + public List Scopes { get; init; } = []; + + public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority); + + public static AuthenticationSettings FromConfiguration(IConfiguration configuration) + { + return configuration.GetSection(SectionName).Get() ?? new AuthenticationSettings(); + } +} diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs index 1028f15..f745d2c 100644 --- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs @@ -3,12 +3,15 @@ namespace CleanModelContextProtocol.Presentation.Extensions; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Application; +using CleanModelContextProtocol.Presentation.Authentication; using CleanModelContextProtocol.Presentation.Completions; using CleanModelContextProtocol.Presentation.Errors; using CleanModelContextProtocol.Presentation.Serialization; using Infrastructure; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.AspNetCore.Authentication; using Serilog; [ExcludeFromCodeCoverage] @@ -38,6 +41,36 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat #endregion Project Dependencies + #region Authentication + + var authentication = AuthenticationSettings.FromConfiguration(builder.Configuration); + + if (authentication.Enabled) + { + _ = builder.Services + .AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme; + }) + .AddJwtBearer(options => + { + options.Authority = authentication.Authority; + options.Audience = authentication.Audience; + options.MapInboundClaims = false; + }) + .AddMcp(options => options.ResourceMetadata = new() + { + Resource = authentication.Audience, + AuthorizationServers = [authentication.Authority], + ScopesSupported = authentication.Scopes, + ResourceName = "Clean Model Context Protocol" + }); + _ = builder.Services.AddAuthorization(); + } + + #endregion Authentication + #region Model Context Protocol _ = builder.Services diff --git a/src/Presentation/Extensions/WebApplicationExtensions.cs b/src/Presentation/Extensions/WebApplicationExtensions.cs index d6c3709..0fe8b1f 100644 --- a/src/Presentation/Extensions/WebApplicationExtensions.cs +++ b/src/Presentation/Extensions/WebApplicationExtensions.cs @@ -1,6 +1,7 @@ namespace CleanModelContextProtocol.Presentation.Extensions; using System.Diagnostics.CodeAnalysis; +using CleanModelContextProtocol.Presentation.Authentication; using Microsoft.AspNetCore.Builder; using Serilog; @@ -17,7 +18,14 @@ public static WebApplication ConfigureApplication(this WebApplication app) #region Model Context Protocol - _ = app.MapMcp("/mcp"); + var mcp = app.MapMcp("/mcp"); + + if (AuthenticationSettings.FromConfiguration(app.Configuration).Enabled) + { + _ = app.UseAuthentication(); + _ = app.UseAuthorization(); + _ = mcp.RequireAuthorization(); + } #endregion Model Context Protocol diff --git a/src/Presentation/Presentation.csproj b/src/Presentation/Presentation.csproj index 544b891..7afb79b 100644 --- a/src/Presentation/Presentation.csproj +++ b/src/Presentation/Presentation.csproj @@ -19,6 +19,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/Presentation/appsettings.json b/src/Presentation/appsettings.json index b6bc552..842e129 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -19,5 +19,10 @@ "Default": "None" } }, + "Authentication": { + "Authority": "", + "Audience": "", + "Scopes": [] + }, "AllowedHosts": "*" } diff --git a/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs b/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs new file mode 100644 index 0000000..0d97ccd --- /dev/null +++ b/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs @@ -0,0 +1,126 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Integration.Authentication; + +using System.Net; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; +using Microsoft.IdentityModel.Tokens; +using ModelContextProtocol.Client; +using ModelContextProtocol.Protocol; +using Shouldly; +using Xunit; + +public class AuthenticationTests : IDisposable +{ + private const string Authority = "https://login.example.com"; + private const string Audience = "https://mcp.example.com"; + + private static readonly SymmetricSecurityKey SigningKey = new(Encoding.UTF8.GetBytes("a-test-signing-key-that-is-long-enough-for-hs256")); + + private readonly ModelContextProtocolApplication application = new( + settings: new Dictionary + { + ["Authentication:Authority"] = Authority, + ["Authentication:Audience"] = Audience, + ["Authentication:Scopes:0"] = "mcp:tools" + }, + configureServices: services => services.PostConfigure(JwtBearerDefaults.AuthenticationScheme, options => + { + options.Configuration = new OpenIdConnectConfiguration { Issuer = Authority }; + options.TokenValidationParameters.IssuerSigningKey = SigningKey; + options.TokenValidationParameters.ValidIssuer = Authority; + })); + + [Fact] + public async Task Mcp_WithoutToken_ShouldReturn_UnauthorizedWithResourceMetadata() + { + // Arrange + using var client = this.application.CreateClient(); + using var content = new StringContent("{}", Encoding.UTF8, "application/json"); + + // Act + using var response = await client.PostAsync(new Uri("http://localhost/mcp"), content); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + response.Headers.WwwAuthenticate.ToString().ShouldContain("resource_metadata=\"http://localhost/.well-known/oauth-protected-resource/mcp\""); + } + + [Fact] + public async Task ResourceMetadata_ShouldReturn_AuthorizationServer() + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var response = await client.GetAsync(new Uri("http://localhost/.well-known/oauth-protected-resource/mcp")); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + + using var metadata = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + metadata.RootElement.GetProperty("resource").GetString().ShouldBe(Audience); + metadata.RootElement.GetProperty("authorization_servers")[0].GetString().ShouldBe(Authority); + metadata.RootElement.GetProperty("scopes_supported")[0].GetString().ShouldBe("mcp:tools"); + } + + [Fact] + public async Task Mcp_WithWrongAudience_ShouldReturn_Unauthorized() + { + // Arrange + using var client = this.application.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken("https://someone-else.example.com")); + using var content = new StringContent("{}", Encoding.UTF8, "application/json"); + + // Act + using var response = await client.PostAsync(new Uri("http://localhost/mcp"), content); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task Mcp_WithToken_ShouldList_Tools() + { + // Arrange + using var httpClient = this.application.CreateClient(); + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(Audience)); + + await using var client = await McpClient.CreateAsync( + new HttpClientTransport( + new HttpClientTransportOptions { Endpoint = new Uri("http://localhost/mcp") }, + httpClient, + null, + false), + new McpClientOptions { ClientInfo = new Implementation { Name = "test-client", Version = "1.0" } }); + + // Act + var tools = await client.ListToolsAsync(); + + // Assert + tools.ShouldNotBeEmpty(); + } + + public void Dispose() + { + this.application.Dispose(); + GC.SuppressFinalize(this); + } + + private static string CreateToken(string audience) + { + return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor + { + Issuer = Authority, + Audience = audience, + Subject = new ClaimsIdentity([new Claim("sub", "test-user")]), + Expires = DateTime.UtcNow.AddMinutes(5), + SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256) + }); + } +} diff --git a/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs b/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs index b312831..c64e1b8 100644 --- a/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs +++ b/tests/Presentation.Tests.Integration/ModelContextProtocolApplication.cs @@ -1,14 +1,29 @@ namespace CleanModelContextProtocol.Presentation.Tests.Integration; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -internal sealed class ModelContextProtocolApplication(string environment = "local") : WebApplicationFactory +internal sealed class ModelContextProtocolApplication( + string environment = "local", + Dictionary settings = null, + Action configureServices = null) : WebApplicationFactory { protected override IHost CreateHost(IHostBuilder builder) { _ = builder.UseEnvironment(environment); + if (settings is not null) + { + _ = builder.ConfigureHostConfiguration(configuration => configuration.AddInMemoryCollection(settings)); + } + + if (configureServices is not null) + { + _ = builder.ConfigureServices(configureServices); + } + return base.CreateHost(builder); } } diff --git a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs new file mode 100644 index 0000000..321813b --- /dev/null +++ b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs @@ -0,0 +1,46 @@ +namespace CleanModelContextProtocol.Presentation.Tests.Unit.Authentication; + +using CleanModelContextProtocol.Presentation.Authentication; +using Microsoft.Extensions.Configuration; +using Shouldly; +using Xunit; + +public class AuthenticationSettingsTests +{ + [Fact] + public void FromConfiguration_ShouldReturn_DisabledSettings_WhenSectionIsMissing() + { + // Arrange + var configuration = new ConfigurationBuilder().Build(); + + // Act + var result = AuthenticationSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeFalse(); + result.Scopes.ShouldBeEmpty(); + } + + [Fact] + public void FromConfiguration_ShouldReturn_EnabledSettings_WhenAuthorityIsSet() + { + // Arrange + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Audience"] = "https://localhost:5001", + ["Authentication:Scopes:0"] = "movies.read", + }) + .Build(); + + // Act + var result = AuthenticationSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeTrue(); + result.Authority.ShouldBe("https://login.example.com"); + result.Audience.ShouldBe("https://localhost:5001"); + result.Scopes.ShouldBe(["movies.read"]); + } +}