|
| 1 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 2 | +using Microsoft.AspNetCore.Builder; |
| 3 | +using Microsoft.AspNetCore.WebUtilities; |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.IdentityModel.Tokens; |
| 6 | +using ModelContextProtocol.AspNetCore.Authentication; |
| 7 | +using ModelContextProtocol.AspNetCore.Tests.Utils; |
| 8 | +using ModelContextProtocol.Authentication; |
| 9 | +using ModelContextProtocol.Client; |
| 10 | +using System.Net; |
| 11 | + |
| 12 | +namespace ModelContextProtocol.AspNetCore.Tests; |
| 13 | + |
| 14 | +public class AuthTests : KestrelInMemoryTest, IAsyncDisposable |
| 15 | +{ |
| 16 | + private const string McpServerUrl = "http://localhost:5000"; |
| 17 | + private const string OAuthServerUrl = "https://localhost:7029"; |
| 18 | + private const string ClientId = "demo-client"; |
| 19 | + |
| 20 | + private readonly CancellationTokenSource _testCts = new(); |
| 21 | + private readonly Task _oAuthRunTask; |
| 22 | + |
| 23 | + public AuthTests(ITestOutputHelper outputHelper) |
| 24 | + : base(outputHelper) |
| 25 | + { |
| 26 | + SocketsHttpHandler.AllowAutoRedirect = false; |
| 27 | + |
| 28 | + var oAuthServerProgram = new TestOAuthServer.Program(XunitLoggerProvider, KestrelInMemoryTransport); |
| 29 | + _oAuthRunTask = oAuthServerProgram.RunServerAsync(cancellationToken: _testCts.Token); |
| 30 | + |
| 31 | + Builder.Services.AddAuthentication(options => |
| 32 | + { |
| 33 | + options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme; |
| 34 | + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; |
| 35 | + }) |
| 36 | + .AddJwtBearer(options => |
| 37 | + { |
| 38 | + options.Backchannel = HttpClient; |
| 39 | + options.Authority = OAuthServerUrl; |
| 40 | + options.TokenValidationParameters = new TokenValidationParameters |
| 41 | + { |
| 42 | + ValidateIssuer = true, |
| 43 | + ValidateAudience = true, |
| 44 | + ValidateLifetime = true, |
| 45 | + ValidateIssuerSigningKey = true, |
| 46 | + ValidAudience = ClientId, |
| 47 | + ValidIssuer = OAuthServerUrl, |
| 48 | + NameClaimType = "name", |
| 49 | + RoleClaimType = "roles" |
| 50 | + }; |
| 51 | + }) |
| 52 | + .AddMcp(options => |
| 53 | + { |
| 54 | + options.ProtectedResourceMetadataProvider = context => |
| 55 | + { |
| 56 | + var metadata = new ProtectedResourceMetadata |
| 57 | + { |
| 58 | + Resource = new Uri(McpServerUrl), |
| 59 | + BearerMethodsSupported = { "header" }, |
| 60 | + AuthorizationServers = { new Uri(OAuthServerUrl) } |
| 61 | + }; |
| 62 | + |
| 63 | + metadata.ScopesSupported.AddRange([ |
| 64 | + "mcp:tools" |
| 65 | + ]); |
| 66 | + |
| 67 | + return metadata; |
| 68 | + }; |
| 69 | + }); |
| 70 | + |
| 71 | + Builder.Services.AddAuthorization(); |
| 72 | + } |
| 73 | + |
| 74 | + public async ValueTask DisposeAsync() |
| 75 | + { |
| 76 | + _testCts.Cancel(); |
| 77 | + try |
| 78 | + { |
| 79 | + await _oAuthRunTask; |
| 80 | + } |
| 81 | + catch (OperationCanceledException) |
| 82 | + { |
| 83 | + } |
| 84 | + finally |
| 85 | + { |
| 86 | + _testCts.Dispose(); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + [Fact] |
| 91 | + public async Task CanAuthenticate() |
| 92 | + { |
| 93 | + Builder.Services.AddMcpServer().WithHttpTransport(); |
| 94 | + |
| 95 | + await using var app = Builder.Build(); |
| 96 | + |
| 97 | + app.MapMcp().RequireAuthorization(); |
| 98 | + |
| 99 | + await app.StartAsync(TestContext.Current.CancellationToken); |
| 100 | + |
| 101 | + var tokenProvider = new GenericOAuthProvider( |
| 102 | + new Uri(McpServerUrl), |
| 103 | + HttpClient, |
| 104 | + clientId: "demo-client", |
| 105 | + clientSecret: "demo-secret", |
| 106 | + redirectUri: new Uri("http://localhost:1179/callback"), |
| 107 | + authorizationRedirectDelegate: HandleAuthorizationUrlAsync, |
| 108 | + loggerFactory: LoggerFactory); |
| 109 | + |
| 110 | + await using var transport = new SseClientTransport(new SseClientTransportOptions() |
| 111 | + { |
| 112 | + Endpoint = new("http://localhost:5000"), |
| 113 | + CredentialProvider = tokenProvider, |
| 114 | + }, HttpClient, LoggerFactory); |
| 115 | + |
| 116 | + await using var client = await McpClientFactory.CreateAsync( |
| 117 | + transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken); |
| 118 | + } |
| 119 | + |
| 120 | + private async Task<string?> HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken) |
| 121 | + { |
| 122 | + var redirectResponse = await HttpClient.GetAsync(authorizationUrl, cancellationToken); |
| 123 | + Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); |
| 124 | + var location = redirectResponse.Headers.Location; |
| 125 | + |
| 126 | + if (location is not null && !string.IsNullOrEmpty(location.Query)) |
| 127 | + { |
| 128 | + var queryParams = QueryHelpers.ParseQuery(location.Query); |
| 129 | + return queryParams["code"]; |
| 130 | + } |
| 131 | + |
| 132 | + return null; |
| 133 | + } |
| 134 | +} |
0 commit comments