Document and demonstrate allowed hosts and CORS policy guidance (#1554)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Stephen Halter <halter73@gmail.com>
This commit is contained in:
Jeff Handley 2026-05-01 19:03:30 -07:00 • committed by GitHub
commit 2c5d1ed2be
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Net.Http.Headers;
using ModelContextProtocol.AspNetCore.Authentication;
using ProtectedMcpServer.Tools;
using System.Net.Http.Headers;
@ -9,6 +10,26 @@ var builder = WebApplication.CreateBuilder(args);
var serverUrl = "http://localhost:7071/";
var inMemoryOAuthServerUrl = "https://localhost:7029";
var allowedOrigins = builder.Configuration.GetSection("Mcp:AllowedOrigins").Get<string[]>() ?? ["http://localhost:5173"];
// This sample runs the MCP server on localhost:7071, and it is intended to be callable from a
// companion web app running on a different host (localhost:5173), while preventing requests from
// other origins. This scenario requires enabling CORS and enabling a restrictive CORS policy.
//
// If your server is not meant for cross-origin browser access, leave CORS disabled.
//
// Only apply a lenient CORS policy if your server is intended to be callable from any browser.
builder.Services.AddCors(options =>
{
options.AddPolicy("McpBrowserClient", policy =>
{
policy.WithOrigins(allowedOrigins)
.WithMethods("POST")
.WithHeaders(HeaderNames.ContentType, HeaderNames.Authorization, "MCP-Protocol-Version")
.WithExposedHeaders(HeaderNames.WWWAuthenticate);
});
});
builder.Services.AddAuthentication(options =>
{
@ -84,11 +105,12 @@ builder.Services.AddHttpClient("WeatherApi", client =>
var app = builder.Build();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
// Use the default MCP policy name that we've configured
app.MapMcp().RequireAuthorization();
app.MapMcp().RequireAuthorization().RequireCors("McpBrowserClient");
Console.WriteLine($"Starting MCP server with authorization at {serverUrl}");
Console.WriteLine($"Using in-memory OAuth server at {inMemoryOAuthServerUrl}");