Skip to content

Commit 3713da6

Browse files
committed
Server configuration
1 parent d1f30f8 commit 3713da6

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

samples/SecureWeatherServer/Program.cs

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using Microsoft.Extensions.Options;
33
using ModelContextProtocol.AspNetCore;
44
using ModelContextProtocol.Protocol.Types;
5+
using ModelContextProtocol.AspNetCore.Auth;
56
using System.Security.Claims;
67
using System.Text.Encodings.Web;
78

@@ -75,8 +76,13 @@
7576
});
7677

7778
// Configure authentication using the built-in authentication system
78-
builder.Services.AddAuthentication("Bearer")
79-
.AddScheme<AuthenticationSchemeOptions, SimpleAuthHandler>("Bearer", options => { });
79+
// Register "Bearer" scheme with our SimpleAuthHandler and set it as the default scheme
80+
builder.Services.AddAuthentication(options =>
81+
{
82+
options.DefaultScheme = "Bearer";
83+
options.DefaultChallengeScheme = "Bearer"; // Ensure challenges use Bearer scheme
84+
})
85+
.AddScheme<AuthenticationSchemeOptions, SimpleAuthHandler>("Bearer", options => { });
8086

8187
// Add authorization policy for MCP
8288
builder.Services.AddAuthorization(options =>
@@ -117,12 +123,17 @@
117123
// In a real app, you'd use a JWT handler or other proper authentication
118124
class SimpleAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
119125
{
126+
// Directly inject the ResourceMetadataService instead of the options
127+
private readonly ResourceMetadataService _resourceMetadataService;
128+
120129
public SimpleAuthHandler(
121130
IOptionsMonitor<AuthenticationSchemeOptions> options,
122131
ILoggerFactory logger,
123-
UrlEncoder encoder)
132+
UrlEncoder encoder,
133+
ResourceMetadataService resourceMetadataService)
124134
: base(options, logger, encoder)
125135
{
136+
_resourceMetadataService = resourceMetadataService;
126137
}
127138

128139
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
@@ -162,4 +173,19 @@ protected override Task<AuthenticateResult> HandleAuthenticateAsync()
162173

163174
return Task.FromResult(AuthenticateResult.Success(ticket));
164175
}
176+
177+
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
178+
{
179+
// Always include the resource_metadata in the WWW-Authenticate header
180+
var baseUrl = $"{Request.Scheme}://{Request.Host}";
181+
var metadataUrl = $"{baseUrl}/.well-known/oauth-protected-resource";
182+
183+
// Add WWW-Authenticate header with resource_metadata
184+
Response.Headers.WWWAuthenticate = $"Bearer resource_metadata=\"{metadataUrl}\"";
185+
186+
// Set 401 status code
187+
Response.StatusCode = 401;
188+
189+
return Task.CompletedTask;
190+
}
165191
}

0 commit comments

Comments
 (0)