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:
parent
0781beafa0
commit
2c5d1ed2be
1 changed files with 288 additions and 9 deletions
|
|
@ -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}");
|
||||
|
|
|
|||
Loading…
Reference in a new issue