Skip to content

Commit e5b1321

Browse files
halter73Copilot
andcommitted
Fix ClientOAuthProvider cold-start refresh when client ID isn't persisted
On a cold start where a durable ITokenCache returns a persisted refresh token but no client ID has been assigned yet (DCR/CIMD clients), GetAccessTokenCoreAsync attempted a token refresh before assigning a client ID, causing CreateTokenRequest -> GetClientIdOrThrow() to throw 'Client ID is not available'. Persist the client registration (client ID, secret, token endpoint auth method) alongside the tokens so a single durable ITokenCache can use the refresh token after a restart, and restore it on a cold start before the refresh attempt. Also guard the refresh block with a client-ID check so the flow falls through to client-ID assignment and the authorization-code flow instead of throwing when no credentials are available. The restore and persistence run inside the provider's _tokenAcquisitionLock (added in #1708), so the shared credential fields are written under the same lock that serializes the rest of the auth state; no new races are introduced. Fixes #1658 Co-authored-by: Copilot App <[email protected]>
1 parent 20c464c commit e5b1321

3 files changed

Lines changed: 223 additions & 3 deletions

File tree

‎src/ModelContextProtocol.Core/Authentication/ClientOAuthProvider.cs‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -373,13 +373,24 @@ private async Task<string> GetAccessTokenCoreAsync(HttpResponseMessage response,
373373
// The existing access token must be invalid to have resulted in a 401 response, but refresh might still work.
374374
var resourceUri = GetResourceUri(protectedResourceMetadata);
375375

376+
// Restore any client registration persisted alongside the tokens. On a cold start a durable
377+
// token cache may hold a refresh token together with the client ID it was issued to, while this
378+
// provider has not assigned a client ID yet. Restoring it here makes the refresh below possible
379+
// and avoids a redundant dynamic client registration in the assignment block.
380+
var cachedTokens = await _tokenCache.GetTokensAsync(cancellationToken).ConfigureAwait(false);
381+
RestoreCachedClientCredentials(cachedTokens);
382+
376383
// Only attempt a token refresh if we haven't attempted to already for this request.
377384
// Also only attempt a token refresh for a 401 Unauthorized responses. Other response status codes
378-
// should not be used for expired access tokens. This is important because 403 forbiden responses can
379-
// be used for incremental consent which cannot be acheived with a simple refresh.
385+
// should not be used for expired access tokens. This is important because 403 forbidden responses can
386+
// be used for incremental consent which cannot be achieved with a simple refresh.
387+
// A refresh also requires a client ID. On a cold start one may not be available yet (and could not
388+
// be restored from the cache), in which case we fall through to the client-ID assignment block and
389+
// the authorization-code flow below rather than throwing.
380390
if (!attemptedRefresh &&
381391
response.StatusCode == System.Net.HttpStatusCode.Unauthorized &&
382-
await _tokenCache.GetTokensAsync(cancellationToken).ConfigureAwait(false) is { RefreshToken: { Length: > 0 } refreshToken })
392+
!string.IsNullOrEmpty(_clientId) &&
393+
cachedTokens is { RefreshToken: { Length: > 0 } refreshToken })
383394
{
384395
var accessToken = await RefreshTokensAsync(refreshToken, resourceUri, authServerMetadata, cancellationToken).ConfigureAwait(false);
385396
if (accessToken is not null)
@@ -749,6 +760,11 @@ private async Task<TokenContainer> HandleSuccessfulTokenResponseAsync(HttpRespon
749760
TokenType = tokenResponse.TokenType,
750761
Scope = tokenResponse.Scope,
751762
ObtainedAt = DateTimeOffset.UtcNow,
763+
// Persist the client registration alongside the tokens so a durable cache can use the
764+
// refresh token after a process restart without re-running dynamic client registration.
765+
ClientId = _clientId,
766+
ClientSecret = _clientSecret,
767+
TokenEndpointAuthMethod = _tokenEndpointAuthMethod,
752768
};
753769

754770
await _tokenCache.StoreTokensAsync(tokens, cancellationToken).ConfigureAwait(false);
@@ -1259,6 +1275,30 @@ private static string ToBase64UrlString(byte[] bytes)
12591275

12601276
private string GetClientIdOrThrow() => _clientId ?? throw new InvalidOperationException("Client ID is not available. This may indicate an issue with dynamic client registration.");
12611277

1278+
/// <summary>
1279+
/// Restores the client registration persisted alongside cached tokens when this provider has not been
1280+
/// assigned a client ID yet. This allows a durable <see cref="ITokenCache"/> to use a refresh token that
1281+
/// survived a process restart without re-running dynamic client registration. An explicitly configured
1282+
/// client ID always takes precedence, so nothing is restored when one is already available.
1283+
/// </summary>
1284+
/// <remarks>
1285+
/// Callers must hold <c>_tokenAcquisitionLock</c>: this writes the shared <c>_clientId</c>,
1286+
/// <c>_clientSecret</c>, and <c>_tokenEndpointAuthMethod</c> fields, which the lock serializes.
1287+
/// </remarks>
1288+
private void RestoreCachedClientCredentials(TokenContainer? tokens)
1289+
{
1290+
if (!string.IsNullOrEmpty(_clientId) || string.IsNullOrEmpty(tokens?.ClientId))
1291+
{
1292+
return;
1293+
}
1294+
1295+
// Assign _clientId last. Callers treat a non-empty _clientId as "registration complete", so the
1296+
// secret and auth method must already be in place before _clientId becomes observable.
1297+
_clientSecret ??= tokens.ClientSecret;
1298+
_tokenEndpointAuthMethod ??= tokens.TokenEndpointAuthMethod;
1299+
_clientId = tokens!.ClientId;
1300+
}
1301+
12621302
[DoesNotReturn]
12631303
private static void ThrowFailedToHandleUnauthorizedResponse(string message) =>
12641304
throw new McpException($"Failed to handle unauthorized response with 'Bearer' scheme. {message}");

‎src/ModelContextProtocol.Core/Authentication/TokenContainer.cs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,39 @@ public sealed class TokenContainer
3535
/// </summary>
3636
public required DateTimeOffset ObtainedAt { get; set; }
3737

38+
/// <summary>
39+
/// Gets or sets the OAuth client ID that these tokens were issued to.
40+
/// </summary>
41+
/// <remarks>
42+
/// This is persisted alongside the tokens so that a durable <see cref="ITokenCache"/> can survive a
43+
/// process restart: on a cold start the client ID is restored from the cache, allowing a persisted
44+
/// <see cref="RefreshToken"/> to be used without re-running dynamic client registration or prompting
45+
/// the user to re-authorize. It reflects the client ID currently in use, whether that was obtained via
46+
/// dynamic client registration, a client-id metadata document, or configured explicitly. On a cold
47+
/// start it is only restored when no client ID has been configured, so an explicitly configured client
48+
/// ID always takes precedence.
49+
/// </remarks>
50+
public string? ClientId { get; set; }
51+
52+
/// <summary>
53+
/// Gets or sets the OAuth client secret that these tokens were issued to, if any.
54+
/// </summary>
55+
/// <remarks>
56+
/// This is persisted alongside <see cref="ClientId"/> so a durable <see cref="ITokenCache"/> can use a
57+
/// persisted <see cref="RefreshToken"/> after a restart. It is only populated when a client secret was
58+
/// issued (for example via dynamic client registration).
59+
/// </remarks>
60+
public string? ClientSecret { get; set; }
61+
62+
/// <summary>
63+
/// Gets or sets the token endpoint authentication method associated with <see cref="ClientId"/>.
64+
/// </summary>
65+
/// <remarks>
66+
/// This is persisted alongside <see cref="ClientId"/> so a refresh performed on a cold start uses the
67+
/// same authentication method that was negotiated when the client was registered (for example
68+
/// <c>none</c> for a public client rather than the default <c>client_secret_post</c>).
69+
/// </remarks>
70+
public string? TokenEndpointAuthMethod { get; set; }
71+
3872
internal bool IsExpired => ExpiresIn is not null && DateTimeOffset.UtcNow >= ObtainedAt.AddSeconds(ExpiresIn.Value);
3973
}

‎tests/ModelContextProtocol.AspNetCore.Tests/OAuth/TokenCacheTests.cs‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,152 @@ public async Task GetTokenAsync_InvalidAccessTokenTriggersRefresh()
187187
Assert.NotEqual("invalid-token", tokenCache.LastStoredToken.AccessToken);
188188
}
189189

190+
[Fact]
191+
public async Task GetTokenAsync_ColdStartWithDynamicRegistration_RefreshesUsingPersistedCredentials()
192+
{
193+
await using var app = await StartMcpServerAsync();
194+
195+
var tokenCache = new TestTokenCache();
196+
var authDelegateCalledInitially = false;
197+
198+
// First "process": no ClientId is configured, so the client registers dynamically.
199+
await using var setupTransport = new HttpClientTransport(new()
200+
{
201+
Endpoint = new(McpServerUrl),
202+
OAuth = new()
203+
{
204+
RedirectUri = new Uri("http://localhost:1179/callback"),
205+
DynamicClientRegistration = new()
206+
{
207+
ClientName = "Test MCP Client",
208+
ClientUri = new Uri("https://example.com"),
209+
},
210+
AuthorizationRedirectDelegate = (uri, redirect, ct) =>
211+
{
212+
authDelegateCalledInitially = true;
213+
return HandleAuthorizationUrlAsync(uri, redirect, ct);
214+
},
215+
TokenCache = tokenCache,
216+
},
217+
}, HttpClient, LoggerFactory);
218+
219+
await using (var setupClient = await McpClient.CreateAsync(setupTransport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken))
220+
{
221+
// Just connecting should trigger dynamic registration, authorization, and storage.
222+
}
223+
224+
Assert.True(authDelegateCalledInitially, "AuthorizationRedirectDelegate should be called for the initial authorization");
225+
Assert.False(TestOAuthServer.HasRefreshedToken, "Token should not have been refreshed yet");
226+
Assert.NotNull(tokenCache.LastStoredToken);
227+
Assert.False(
228+
string.IsNullOrEmpty(tokenCache.LastStoredToken.ClientId),
229+
"The dynamically registered client ID should be persisted alongside the tokens");
230+
231+
// Simulate a cold start: the access token is no longer valid, but the refresh token persists.
232+
// The new provider has no client ID configured and must restore it from the cache to refresh
233+
// instead of throwing "Client ID is not available".
234+
tokenCache.LastStoredToken.AccessToken = "invalid-token";
235+
var authDelegateCalledAgain = false;
236+
237+
await using var transport = new HttpClientTransport(new()
238+
{
239+
Endpoint = new(McpServerUrl),
240+
OAuth = new()
241+
{
242+
RedirectUri = new Uri("http://localhost:1179/callback"),
243+
DynamicClientRegistration = new()
244+
{
245+
ClientName = "Test MCP Client",
246+
ClientUri = new Uri("https://example.com"),
247+
},
248+
AuthorizationRedirectDelegate = (uri, redirect, ct) =>
249+
{
250+
authDelegateCalledAgain = true;
251+
return HandleAuthorizationUrlAsync(uri, redirect, ct);
252+
},
253+
TokenCache = tokenCache,
254+
},
255+
}, HttpClient, LoggerFactory);
256+
257+
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
258+
259+
Assert.False(authDelegateCalledAgain, "AuthorizationRedirectDelegate should not be called when the persisted refresh token can be used");
260+
Assert.True(TestOAuthServer.HasRefreshedToken, "Token should have been refreshed using the persisted client credentials");
261+
Assert.NotEqual("invalid-token", tokenCache.LastStoredToken.AccessToken);
262+
}
263+
264+
[Fact]
265+
public async Task GetTokenAsync_ColdStartWithoutPersistedClientId_FallsBackToReauthorization()
266+
{
267+
await using var app = await StartMcpServerAsync();
268+
269+
var tokenCache = new TestTokenCache();
270+
var authDelegateCalledInitially = false;
271+
272+
await using var setupTransport = new HttpClientTransport(new()
273+
{
274+
Endpoint = new(McpServerUrl),
275+
OAuth = new()
276+
{
277+
RedirectUri = new Uri("http://localhost:1179/callback"),
278+
DynamicClientRegistration = new()
279+
{
280+
ClientName = "Test MCP Client",
281+
ClientUri = new Uri("https://example.com"),
282+
},
283+
AuthorizationRedirectDelegate = (uri, redirect, ct) =>
284+
{
285+
authDelegateCalledInitially = true;
286+
return HandleAuthorizationUrlAsync(uri, redirect, ct);
287+
},
288+
TokenCache = tokenCache,
289+
},
290+
}, HttpClient, LoggerFactory);
291+
292+
await using (var setupClient = await McpClient.CreateAsync(setupTransport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken))
293+
{
294+
}
295+
296+
Assert.True(authDelegateCalledInitially, "AuthorizationRedirectDelegate should be called for the initial authorization");
297+
Assert.NotNull(tokenCache.LastStoredToken);
298+
299+
// Simulate a durable cache that persisted tokens but not the client registration (for example
300+
// an entry written by an older version). On a cold start the provider cannot refresh without a
301+
// client ID and must fall back to a fresh authorization rather than throwing.
302+
tokenCache.LastStoredToken.AccessToken = "invalid-token";
303+
tokenCache.LastStoredToken.ClientId = null;
304+
tokenCache.LastStoredToken.ClientSecret = null;
305+
tokenCache.LastStoredToken.TokenEndpointAuthMethod = null;
306+
var authDelegateCalledAgain = false;
307+
308+
await using var transport = new HttpClientTransport(new()
309+
{
310+
Endpoint = new(McpServerUrl),
311+
OAuth = new()
312+
{
313+
RedirectUri = new Uri("http://localhost:1179/callback"),
314+
DynamicClientRegistration = new()
315+
{
316+
ClientName = "Test MCP Client",
317+
ClientUri = new Uri("https://example.com"),
318+
},
319+
AuthorizationRedirectDelegate = (uri, redirect, ct) =>
320+
{
321+
authDelegateCalledAgain = true;
322+
return HandleAuthorizationUrlAsync(uri, redirect, ct);
323+
},
324+
TokenCache = tokenCache,
325+
},
326+
}, HttpClient, LoggerFactory);
327+
328+
// Should not throw "Client ID is not available"; instead re-authorizes via dynamic
329+
// registration and the authorization-code flow.
330+
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
331+
332+
Assert.True(authDelegateCalledAgain, "AuthorizationRedirectDelegate should be called to re-authorize when no client ID is available to refresh");
333+
Assert.False(TestOAuthServer.HasRefreshedToken, "A refresh should not be attempted without a client ID");
334+
}
335+
190336
private TokenContainer CreateInvalidToken()
191337
{
192338
return new TokenContainer

0 commit comments

Comments
 (0)