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
|
|
@ -6,6 +6,23 @@ using AspNetCoreMcpServer.Resources;
|
|||
using System.Net.Http.Headers;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var allowedOrigins = builder.Configuration.GetSection("Mcp:AllowedOrigins").Get<string[]>() ?? ["http://localhost:5173"];
|
||||
|
||||
// Only enable CORS if you intentionally want browser-based cross-origin access to this server.
|
||||
// Keep the allowlist narrowly scoped to known origins. Broad CORS settings weaken security.
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("McpBrowserClient", policy =>
|
||||
{
|
||||
policy.WithOrigins(allowedOrigins)
|
||||
.WithMethods("GET", "POST", "DELETE")
|
||||
// Browsers can send Accept without extra CORS configuration. These are the MCP-specific
|
||||
// and non-safelisted headers the browser-based client needs for stateful Streamable HTTP.
|
||||
.WithHeaders("Content-Type", "MCP-Protocol-Version", "Mcp-Session-Id")
|
||||
.WithExposedHeaders("Mcp-Session-Id");
|
||||
});
|
||||
});
|
||||
|
||||
// Note: This sample uses SampleLlmTool which calls server.AsSamplingChatClient() to send
|
||||
// a server-to-client sampling request. This requires stateful (session-based) mode. Set
|
||||
// Stateless = false explicitly for forward compatibility in case the default changes.
|
||||
|
|
@ -36,6 +53,7 @@ builder.Services.AddHttpClient("WeatherApi", client =>
|
|||
|
||||
var app = builder.Build();
|
||||
|
||||
app.MapMcp();
|
||||
app.UseCors();
|
||||
app.MapMcp().RequireCors("McpBrowserClient");
|
||||
|
||||
app.Run();
|
||||
|
|
|
|||
Loading…
Reference in a new issue