File tree Expand file tree Collapse file tree 2 files changed +37
-4
lines changed
samples/ProtectedMCPServer
src/ModelContextProtocol.AspNetCore/Auth Expand file tree Collapse file tree 2 files changed +37
-4
lines changed Original file line number Diff line number Diff line change 7777// Add authorization services
7878builder . Services . AddAuthorization ( options =>
7979{
80- options . AddPolicy ( McpAuthenticationDefaults . AuthenticationScheme , policy =>
81- {
82- policy . RequireAuthenticatedUser ( ) ;
83- } ) ;
80+ options . AddMcpPolicy ( ) ;
8481} ) ;
8582
8683// Configure MCP Server
Original file line number Diff line number Diff line change 1+ using Microsoft . AspNetCore . Authorization ;
2+ using ModelContextProtocol . AspNetCore . Auth ;
3+
4+ namespace Microsoft . Extensions . DependencyInjection ;
5+
6+ /// <summary>
7+ /// Extension methods for adding MCP authorization policies to ASP.NET Core applications.
8+ /// </summary>
9+ public static class McpAuthorizationExtensions
10+ {
11+ /// <summary>
12+ /// Adds a preconfigured MCP policy to the authorization options.
13+ /// </summary>
14+ /// <param name="options">The authorization options.</param>
15+ /// <param name="policyName">The name of the policy to add. Default is <see cref="McpAuthenticationDefaults.AuthenticationScheme"/>.</param>
16+ /// <param name="configurePolicy">An optional action to further configure the policy builder.</param>
17+ /// <returns>The authorization options for chaining.</returns>
18+ public static AuthorizationOptions AddMcpPolicy (
19+ this AuthorizationOptions options ,
20+ string policyName = McpAuthenticationDefaults . AuthenticationScheme ,
21+ Action < AuthorizationPolicyBuilder > ? configurePolicy = null )
22+ {
23+ // Create a policy builder with default MCP configuration
24+ var policyBuilder = new AuthorizationPolicyBuilder ( )
25+ . RequireAuthenticatedUser ( )
26+ . AddAuthenticationSchemes ( McpAuthenticationDefaults . AuthenticationScheme ) ;
27+
28+ // Allow additional configuration if provided
29+ configurePolicy ? . Invoke ( policyBuilder ) ;
30+
31+ // Add the configured policy
32+ options . AddPolicy ( policyName , policyBuilder . Build ( ) ) ;
33+
34+ return options ;
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments