From b6a3183ca82acff030f4b051a05eaa56b9752342 Mon Sep 17 00:00:00 2001 From: Matthew John Cheetham Date: Mon, 9 Nov 2026 12:46:41 +0000 Subject: [PATCH 1/3] oauth: use LF line endings in the repo We typically store files with the LF line ending in our repo. The OAuth client file was stored with CRLF in error. Fix that. Signed-off-by: Matthew John Cheetham --- src/Core/Authentication/OAuth/OAuth2Client.cs | 900 +++++++++--------- 1 file changed, 450 insertions(+), 450 deletions(-) diff --git a/src/Core/Authentication/OAuth/OAuth2Client.cs b/src/Core/Authentication/OAuth/OAuth2Client.cs index 1089fae1d..d9bf96a5c 100644 --- a/src/Core/Authentication/OAuth/OAuth2Client.cs +++ b/src/Core/Authentication/OAuth/OAuth2Client.cs @@ -1,450 +1,450 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading; -using System.Threading.Tasks; -using GitCredentialManager.Authentication.OAuth.Json; -using System.Text.Json; -using System.Text.Json.Serialization.Metadata; - -namespace GitCredentialManager.Authentication.OAuth -{ - /// - /// Represents an OAuth2 client application that can perform the basic flows outlined in RFC 6749, - /// as well as extensions such as OAuth2 Device Authorization Grant (RFC 8628). - /// - public interface IOAuth2Client - { - /// - /// Retrieve an authorization code grant using a user agent. - /// - /// Scopes to request. - /// User agent to use to start the authorization code grant flow. - /// Extra parameters to add to the URL query component. - /// Token to cancel the operation. - /// Authorization code. - Task GetAuthorizationCodeAsync( - IEnumerable scopes, - IOAuth2WebBrowser browser, - IDictionary extraQueryParams, - CancellationToken ct - ); - - /// - /// Retrieve a device code grant. - /// - /// Scopes to request. - /// Token to cancel the operation. - /// Thrown if the client has not been configured with a device authorization endpoint. - /// Device code grant result. - Task GetDeviceCodeAsync(IEnumerable scopes, CancellationToken ct); - - /// - /// Exchange an authorization code acquired from for an access token. - /// - /// Authorization code grant result. - /// Token to cancel the operation. - /// Token result. - Task GetTokenByAuthorizationCodeAsync(OAuth2AuthorizationCodeResult authorizationCodeResult, CancellationToken ct); - - /// - /// Use a refresh token to get a new access token. - /// - /// Refresh token. - /// Token to cancel the operation. - /// Token result. - Task GetTokenByRefreshTokenAsync(string refreshToken, CancellationToken ct); - - /// - /// Exchange a device code grant acquired from for an access token. - /// - /// Device code grant result. - /// Token to cancel the operation. - /// Token result. - Task GetTokenByDeviceCodeAsync(OAuth2DeviceCodeResult deviceCodeResult, CancellationToken ct); - } - - public class OAuth2Client : IOAuth2Client - { - private readonly HttpClient _httpClient; - private readonly OAuth2ServerEndpoints _endpoints; - private readonly Uri _redirectUri; - private readonly string _clientId; - private readonly string _clientSecret; - private readonly bool _addAuthHeader; - private readonly OAuth2ResponseMode _responseMode; - - private IOAuth2CodeGenerator _codeGenerator; - - public OAuth2Client(HttpClient httpClient, - OAuth2ServerEndpoints endpoints, - string clientId, - Uri redirectUri = null, - string clientSecret = null, - bool addAuthHeader = true, - OAuth2ResponseMode responseMode = OAuth2ResponseMode.Default) - { - _httpClient = httpClient; - _endpoints = endpoints; - _clientId = clientId; - _redirectUri = redirectUri; - _clientSecret = clientSecret; - _addAuthHeader = addAuthHeader; - _responseMode = responseMode; - } - - public IOAuth2CodeGenerator CodeGenerator - { - get => _codeGenerator ?? (_codeGenerator = new OAuth2CryptographicCodeGenerator()); - set => _codeGenerator = value; - } - - #region IOAuth2Client - - public async Task GetAuthorizationCodeAsync(IEnumerable scopes, - IOAuth2WebBrowser browser, IDictionary extraQueryParams, CancellationToken ct) - { - using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "get_authcode"); - - string state = CodeGenerator.CreateNonce(); - string codeVerifier = CodeGenerator.CreatePkceCodeVerifier(); - string codeChallenge = CodeGenerator.CreatePkceCodeChallenge(OAuth2PkceChallengeMethod.Sha256, codeVerifier); - - var queryParams = new Dictionary - { - [OAuth2Constants.AuthorizationEndpoint.ResponseTypeParameter] = - OAuth2Constants.AuthorizationEndpoint.AuthorizationCodeResponseType, - [OAuth2Constants.ClientIdParameter] = _clientId, - [OAuth2Constants.AuthorizationEndpoint.StateParameter] = state, - [OAuth2Constants.AuthorizationEndpoint.PkceChallengeMethodParameter] = - OAuth2Constants.AuthorizationEndpoint.PkceChallengeMethodS256, - [OAuth2Constants.AuthorizationEndpoint.PkceChallengeParameter] = codeChallenge - }; - - // Only send the parameter when requesting a non-default mode to keep the request unchanged otherwise. - if (_responseMode != OAuth2ResponseMode.Default) - { - queryParams[OAuth2Constants.AuthorizationEndpoint.ResponseModeParameter] = - _responseMode.GetParameterValue(); - } - - if (extraQueryParams?.Count > 0) - { - foreach (var kvp in extraQueryParams) - { - if (queryParams.ContainsKey(kvp.Key)) - { - throw new ArgumentException( - $"Extra query parameter '{kvp.Key}' would override required standard OAuth parameters.", - nameof(extraQueryParams)); - } - - queryParams[kvp.Key] = kvp.Value; - } - } - - Uri redirectUri = null; - if (_redirectUri != null) - { - redirectUri = browser.UpdateRedirectUri(_redirectUri); - - // We must use the .OriginalString property here over .ToString() because OAuth requires the redirect - // URLs to be compared exactly, respecting missing/present trailing slashes, byte-for-byte. - queryParams[OAuth2Constants.RedirectUriParameter] = redirectUri.OriginalString; - } - - string scopesStr = string.Join(" ", scopes); - if (!string.IsNullOrWhiteSpace(scopesStr)) - { - queryParams[OAuth2Constants.ScopeParameter] = scopesStr; - } - - var authorizationUriBuilder = new UriBuilder(_endpoints.AuthorizationEndpoint) - { - Query = queryParams.ToQueryString() - }; - - Uri authorizationUri = authorizationUriBuilder.Uri; - - // Open the browser at the request URI to start the authorization code grant flow, and - // intercept the response parameters delivered to the redirect URI. - IDictionary responseParams; - using (Trace2.StartRegion(OAuth2Constants.Trace2Category, "browser")) - { - responseParams = await browser.GetAuthenticationResponseAsync(authorizationUri, redirectUri, _responseMode, ct); - } - - // Check for errors serious enough we should terminate the flow, such as if the state value returned does - // not match the one we passed. This indicates a badly implemented Authorization Server, or worse, some - // form of failed MITM or replay attack. - if (!responseParams.TryGetValue(OAuth2Constants.AuthorizationGrantResponse.StateParameter, out string replyState)) - { - throw new OAuth2Exception( - $"Missing '{OAuth2Constants.AuthorizationGrantResponse.StateParameter}' in response."); - } - if (!StringComparer.Ordinal.Equals(state, replyState)) - { - throw new OAuth2Exception( - $"Invalid '{OAuth2Constants.AuthorizationGrantResponse.StateParameter}' in response; does not match the request."); - } - - // We expect to have the auth code in the response otherwise terminate the flow (we failed authentication for some reason) - if (!responseParams.TryGetValue(OAuth2Constants.AuthorizationGrantResponse.AuthorizationCodeParameter, out string authCode)) - { - throw new OAuth2Exception( - $"Missing '{OAuth2Constants.AuthorizationGrantResponse.AuthorizationCodeParameter}' in response."); - } - - return new OAuth2AuthorizationCodeResult(authCode, redirectUri, codeVerifier); - } - - public async Task GetDeviceCodeAsync(IEnumerable scopes, CancellationToken ct) - { - using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "get_devicecode"); - - if (_endpoints.DeviceAuthorizationEndpoint is null) - { - throw new InvalidOperationException( - "No device authorization endpoint has been configured for this client."); - } - - string scopesStr = string.Join(" ", scopes); - - var formData = new Dictionary - { - [OAuth2Constants.ClientIdParameter] = _clientId - }; - - if (!string.IsNullOrWhiteSpace(scopesStr)) - { - formData[OAuth2Constants.ScopeParameter] = scopesStr; - } - - using (HttpContent requestContent = new FormUrlEncodedContent(formData)) - using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.DeviceAuthorizationEndpoint, requestContent)) - using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) - { - string json = await response.Content.ReadAsStringAsync(); - - if (response.IsSuccessStatusCode && TryDeserializeJson(json, OAuthJsonContext.Default.DeviceAuthorizationEndpointResponseJson, out DeviceAuthorizationEndpointResponseJson jsonObj)) - { - return jsonObj.ToResult(); - } - - throw CreateExceptionFromResponse(json); - } - } - - public async Task GetTokenByAuthorizationCodeAsync(OAuth2AuthorizationCodeResult authorizationCodeResult, CancellationToken ct) - { - using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "token_by_authcode"); - - var formData = new Dictionary - { - [OAuth2Constants.TokenEndpoint.GrantTypeParameter] = OAuth2Constants.TokenEndpoint.AuthorizationCodeGrantType, - [OAuth2Constants.TokenEndpoint.AuthorizationCodeParameter] = authorizationCodeResult.Code, - [OAuth2Constants.TokenEndpoint.PkceVerifierParameter] = authorizationCodeResult.CodeVerifier, - [OAuth2Constants.ClientIdParameter] = _clientId, - [OAuth2Constants.ClientSecretParameter] = _clientSecret - }; - - if (authorizationCodeResult.RedirectUri != null) - { - formData[OAuth2Constants.RedirectUriParameter] = authorizationCodeResult.RedirectUri.OriginalString; - } - - if (authorizationCodeResult.CodeVerifier != null) - { - formData[OAuth2Constants.TokenEndpoint.PkceVerifierParameter] = authorizationCodeResult.CodeVerifier; - } - - using (HttpContent requestContent = new FormUrlEncodedContent(formData)) - using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent, _addAuthHeader)) - using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) - { - string json = await response.Content.ReadAsStringAsync(); - - if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) - { - return result; - } - - throw CreateExceptionFromResponse(json); - } - } - - public async Task GetTokenByRefreshTokenAsync(string refreshToken, CancellationToken ct) - { - using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "token_by_refresh"); - - var formData = new Dictionary - { - [OAuth2Constants.TokenEndpoint.GrantTypeParameter] = OAuth2Constants.TokenEndpoint.RefreshTokenGrantType, - [OAuth2Constants.TokenEndpoint.RefreshTokenParameter] = refreshToken, - [OAuth2Constants.ClientIdParameter] = _clientId, - [OAuth2Constants.ClientSecretParameter] = _clientSecret - }; - - if (_redirectUri != null) - { - formData[OAuth2Constants.RedirectUriParameter] = _redirectUri.ToString(); - } - - using (HttpContent requestContent = new FormUrlEncodedContent(formData)) - using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent, _addAuthHeader)) - using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) - { - string json = await response.Content.ReadAsStringAsync(); - - if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) - { - return result; - } - - throw CreateExceptionFromResponse(json); - } - } - - public async Task GetTokenByDeviceCodeAsync(OAuth2DeviceCodeResult deviceCodeResult, CancellationToken ct) - { - using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "token_by_devicecode"); - - var formData = new Dictionary - { - [OAuth2Constants.DeviceAuthorization.GrantTypeParameter] = OAuth2Constants.DeviceAuthorization.DeviceCodeGrantType, - [OAuth2Constants.DeviceAuthorization.DeviceCodeParameter] = deviceCodeResult.DeviceCode, - [OAuth2Constants.ClientIdParameter] = _clientId, - }; - - TimeSpan retryInterval = deviceCodeResult.PollingInterval; - while (true) - { - ct.ThrowIfCancellationRequested(); - - try - { - using (HttpContent requestContent = new FormUrlEncodedContent(formData)) - using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent)) - using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) - { - string json = await response.Content.ReadAsStringAsync(); - - if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) - { - return result; - } - - TryDeserializeJson(json, OAuthJsonContext.Default.ErrorResponseJson, out ErrorResponseJson error); - - switch (error?.Error) - { - case OAuth2Constants.DeviceAuthorization.Errors.AuthorizationPending: - // Retry with the current polling interval value - break; - case OAuth2Constants.DeviceAuthorization.Errors.SlowDown: - // We must increase the polling interval by 5 seconds - retryInterval = retryInterval.Add(TimeSpan.FromSeconds(5)); - break; - default: - // For all other errors do not retry - throw CreateExceptionFromResponse(json); - } - } - } - catch (TimeoutException) - { - // Back-off exponentially (2 * x = x + x) - retryInterval += retryInterval; - } - - // Wait the polling interval before retrying - await Task.Delay(retryInterval, ct); - } - } - - #endregion - - #region Extension Points - - protected virtual bool TryCreateTokenEndpointResult(string json, out OAuth2TokenResult result) - { - if (TryDeserializeJson(json, - OAuthJsonContext.Default.TokenEndpointResponseJson, - out TokenEndpointResponseJson jsonObj)) - { - result = jsonObj.ToResult(); - return true; - } - - result = null; - return false; - } - - protected virtual bool TryCreateExceptionFromResponse(string json, out OAuth2Exception exception) - { - if (TryDeserializeJson(json, OAuthJsonContext.Default.ErrorResponseJson, out ErrorResponseJson obj)) - { - exception = obj.ToException(); - return true; - } - - exception = null; - return false; - } - - #endregion - - #region Helpers - - private HttpRequestMessage CreateRequestMessage(HttpMethod method, Uri requestUri, HttpContent content = null, bool addAuthHeader = false) - { - var request = new HttpRequestMessage(method, requestUri) {Content = content}; - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.Http.MimeTypeJson)); - - if (addAuthHeader && !string.IsNullOrEmpty(_clientSecret)) - { - request.AddBasicAuthenticationHeader(_clientId, _clientSecret); - } - - return request; - } - - protected Exception CreateExceptionFromResponse(string json) - { - if (TryCreateExceptionFromResponse(json, out OAuth2Exception exception)) - { - return exception; - } - - var format = "Unknown OAuth error: {0}"; - var message = string.Format(format, json); - return new OAuth2Exception(message); - } - - protected static bool TryDeserializeJson(string json, JsonTypeInfo typeInfo, out T obj) - { - try - { - obj = JsonSerializer.Deserialize(json, typeInfo); - return true; - } - catch - { - obj = default; - return false; - } - } - - #endregion - } - - public static class OAuth2ClientExtensions - { - public static Task GetAuthorizationCodeAsync( - this IOAuth2Client client, IEnumerable scopes, IOAuth2WebBrowser browser, CancellationToken ct) - { - return client.GetAuthorizationCodeAsync(scopes, browser, null, ct); - } - } -} +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +using GitCredentialManager.Authentication.OAuth.Json; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace GitCredentialManager.Authentication.OAuth +{ + /// + /// Represents an OAuth2 client application that can perform the basic flows outlined in RFC 6749, + /// as well as extensions such as OAuth2 Device Authorization Grant (RFC 8628). + /// + public interface IOAuth2Client + { + /// + /// Retrieve an authorization code grant using a user agent. + /// + /// Scopes to request. + /// User agent to use to start the authorization code grant flow. + /// Extra parameters to add to the URL query component. + /// Token to cancel the operation. + /// Authorization code. + Task GetAuthorizationCodeAsync( + IEnumerable scopes, + IOAuth2WebBrowser browser, + IDictionary extraQueryParams, + CancellationToken ct + ); + + /// + /// Retrieve a device code grant. + /// + /// Scopes to request. + /// Token to cancel the operation. + /// Thrown if the client has not been configured with a device authorization endpoint. + /// Device code grant result. + Task GetDeviceCodeAsync(IEnumerable scopes, CancellationToken ct); + + /// + /// Exchange an authorization code acquired from for an access token. + /// + /// Authorization code grant result. + /// Token to cancel the operation. + /// Token result. + Task GetTokenByAuthorizationCodeAsync(OAuth2AuthorizationCodeResult authorizationCodeResult, CancellationToken ct); + + /// + /// Use a refresh token to get a new access token. + /// + /// Refresh token. + /// Token to cancel the operation. + /// Token result. + Task GetTokenByRefreshTokenAsync(string refreshToken, CancellationToken ct); + + /// + /// Exchange a device code grant acquired from for an access token. + /// + /// Device code grant result. + /// Token to cancel the operation. + /// Token result. + Task GetTokenByDeviceCodeAsync(OAuth2DeviceCodeResult deviceCodeResult, CancellationToken ct); + } + + public class OAuth2Client : IOAuth2Client + { + private readonly HttpClient _httpClient; + private readonly OAuth2ServerEndpoints _endpoints; + private readonly Uri _redirectUri; + private readonly string _clientId; + private readonly string _clientSecret; + private readonly bool _addAuthHeader; + private readonly OAuth2ResponseMode _responseMode; + + private IOAuth2CodeGenerator _codeGenerator; + + public OAuth2Client(HttpClient httpClient, + OAuth2ServerEndpoints endpoints, + string clientId, + Uri redirectUri = null, + string clientSecret = null, + bool addAuthHeader = true, + OAuth2ResponseMode responseMode = OAuth2ResponseMode.Default) + { + _httpClient = httpClient; + _endpoints = endpoints; + _clientId = clientId; + _redirectUri = redirectUri; + _clientSecret = clientSecret; + _addAuthHeader = addAuthHeader; + _responseMode = responseMode; + } + + public IOAuth2CodeGenerator CodeGenerator + { + get => _codeGenerator ?? (_codeGenerator = new OAuth2CryptographicCodeGenerator()); + set => _codeGenerator = value; + } + + #region IOAuth2Client + + public async Task GetAuthorizationCodeAsync(IEnumerable scopes, + IOAuth2WebBrowser browser, IDictionary extraQueryParams, CancellationToken ct) + { + using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "get_authcode"); + + string state = CodeGenerator.CreateNonce(); + string codeVerifier = CodeGenerator.CreatePkceCodeVerifier(); + string codeChallenge = CodeGenerator.CreatePkceCodeChallenge(OAuth2PkceChallengeMethod.Sha256, codeVerifier); + + var queryParams = new Dictionary + { + [OAuth2Constants.AuthorizationEndpoint.ResponseTypeParameter] = + OAuth2Constants.AuthorizationEndpoint.AuthorizationCodeResponseType, + [OAuth2Constants.ClientIdParameter] = _clientId, + [OAuth2Constants.AuthorizationEndpoint.StateParameter] = state, + [OAuth2Constants.AuthorizationEndpoint.PkceChallengeMethodParameter] = + OAuth2Constants.AuthorizationEndpoint.PkceChallengeMethodS256, + [OAuth2Constants.AuthorizationEndpoint.PkceChallengeParameter] = codeChallenge + }; + + // Only send the parameter when requesting a non-default mode to keep the request unchanged otherwise. + if (_responseMode != OAuth2ResponseMode.Default) + { + queryParams[OAuth2Constants.AuthorizationEndpoint.ResponseModeParameter] = + _responseMode.GetParameterValue(); + } + + if (extraQueryParams?.Count > 0) + { + foreach (var kvp in extraQueryParams) + { + if (queryParams.ContainsKey(kvp.Key)) + { + throw new ArgumentException( + $"Extra query parameter '{kvp.Key}' would override required standard OAuth parameters.", + nameof(extraQueryParams)); + } + + queryParams[kvp.Key] = kvp.Value; + } + } + + Uri redirectUri = null; + if (_redirectUri != null) + { + redirectUri = browser.UpdateRedirectUri(_redirectUri); + + // We must use the .OriginalString property here over .ToString() because OAuth requires the redirect + // URLs to be compared exactly, respecting missing/present trailing slashes, byte-for-byte. + queryParams[OAuth2Constants.RedirectUriParameter] = redirectUri.OriginalString; + } + + string scopesStr = string.Join(" ", scopes); + if (!string.IsNullOrWhiteSpace(scopesStr)) + { + queryParams[OAuth2Constants.ScopeParameter] = scopesStr; + } + + var authorizationUriBuilder = new UriBuilder(_endpoints.AuthorizationEndpoint) + { + Query = queryParams.ToQueryString() + }; + + Uri authorizationUri = authorizationUriBuilder.Uri; + + // Open the browser at the request URI to start the authorization code grant flow, and + // intercept the response parameters delivered to the redirect URI. + IDictionary responseParams; + using (Trace2.StartRegion(OAuth2Constants.Trace2Category, "browser")) + { + responseParams = await browser.GetAuthenticationResponseAsync(authorizationUri, redirectUri, _responseMode, ct); + } + + // Check for errors serious enough we should terminate the flow, such as if the state value returned does + // not match the one we passed. This indicates a badly implemented Authorization Server, or worse, some + // form of failed MITM or replay attack. + if (!responseParams.TryGetValue(OAuth2Constants.AuthorizationGrantResponse.StateParameter, out string replyState)) + { + throw new OAuth2Exception( + $"Missing '{OAuth2Constants.AuthorizationGrantResponse.StateParameter}' in response."); + } + if (!StringComparer.Ordinal.Equals(state, replyState)) + { + throw new OAuth2Exception( + $"Invalid '{OAuth2Constants.AuthorizationGrantResponse.StateParameter}' in response; does not match the request."); + } + + // We expect to have the auth code in the response otherwise terminate the flow (we failed authentication for some reason) + if (!responseParams.TryGetValue(OAuth2Constants.AuthorizationGrantResponse.AuthorizationCodeParameter, out string authCode)) + { + throw new OAuth2Exception( + $"Missing '{OAuth2Constants.AuthorizationGrantResponse.AuthorizationCodeParameter}' in response."); + } + + return new OAuth2AuthorizationCodeResult(authCode, redirectUri, codeVerifier); + } + + public async Task GetDeviceCodeAsync(IEnumerable scopes, CancellationToken ct) + { + using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "get_devicecode"); + + if (_endpoints.DeviceAuthorizationEndpoint is null) + { + throw new InvalidOperationException( + "No device authorization endpoint has been configured for this client."); + } + + string scopesStr = string.Join(" ", scopes); + + var formData = new Dictionary + { + [OAuth2Constants.ClientIdParameter] = _clientId + }; + + if (!string.IsNullOrWhiteSpace(scopesStr)) + { + formData[OAuth2Constants.ScopeParameter] = scopesStr; + } + + using (HttpContent requestContent = new FormUrlEncodedContent(formData)) + using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.DeviceAuthorizationEndpoint, requestContent)) + using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) + { + string json = await response.Content.ReadAsStringAsync(); + + if (response.IsSuccessStatusCode && TryDeserializeJson(json, OAuthJsonContext.Default.DeviceAuthorizationEndpointResponseJson, out DeviceAuthorizationEndpointResponseJson jsonObj)) + { + return jsonObj.ToResult(); + } + + throw CreateExceptionFromResponse(json); + } + } + + public async Task GetTokenByAuthorizationCodeAsync(OAuth2AuthorizationCodeResult authorizationCodeResult, CancellationToken ct) + { + using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "token_by_authcode"); + + var formData = new Dictionary + { + [OAuth2Constants.TokenEndpoint.GrantTypeParameter] = OAuth2Constants.TokenEndpoint.AuthorizationCodeGrantType, + [OAuth2Constants.TokenEndpoint.AuthorizationCodeParameter] = authorizationCodeResult.Code, + [OAuth2Constants.TokenEndpoint.PkceVerifierParameter] = authorizationCodeResult.CodeVerifier, + [OAuth2Constants.ClientIdParameter] = _clientId, + [OAuth2Constants.ClientSecretParameter] = _clientSecret + }; + + if (authorizationCodeResult.RedirectUri != null) + { + formData[OAuth2Constants.RedirectUriParameter] = authorizationCodeResult.RedirectUri.OriginalString; + } + + if (authorizationCodeResult.CodeVerifier != null) + { + formData[OAuth2Constants.TokenEndpoint.PkceVerifierParameter] = authorizationCodeResult.CodeVerifier; + } + + using (HttpContent requestContent = new FormUrlEncodedContent(formData)) + using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent, _addAuthHeader)) + using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) + { + string json = await response.Content.ReadAsStringAsync(); + + if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) + { + return result; + } + + throw CreateExceptionFromResponse(json); + } + } + + public async Task GetTokenByRefreshTokenAsync(string refreshToken, CancellationToken ct) + { + using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "token_by_refresh"); + + var formData = new Dictionary + { + [OAuth2Constants.TokenEndpoint.GrantTypeParameter] = OAuth2Constants.TokenEndpoint.RefreshTokenGrantType, + [OAuth2Constants.TokenEndpoint.RefreshTokenParameter] = refreshToken, + [OAuth2Constants.ClientIdParameter] = _clientId, + [OAuth2Constants.ClientSecretParameter] = _clientSecret + }; + + if (_redirectUri != null) + { + formData[OAuth2Constants.RedirectUriParameter] = _redirectUri.ToString(); + } + + using (HttpContent requestContent = new FormUrlEncodedContent(formData)) + using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent, _addAuthHeader)) + using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) + { + string json = await response.Content.ReadAsStringAsync(); + + if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) + { + return result; + } + + throw CreateExceptionFromResponse(json); + } + } + + public async Task GetTokenByDeviceCodeAsync(OAuth2DeviceCodeResult deviceCodeResult, CancellationToken ct) + { + using IDisposable region = Trace2.StartRegion(OAuth2Constants.Trace2Category, "token_by_devicecode"); + + var formData = new Dictionary + { + [OAuth2Constants.DeviceAuthorization.GrantTypeParameter] = OAuth2Constants.DeviceAuthorization.DeviceCodeGrantType, + [OAuth2Constants.DeviceAuthorization.DeviceCodeParameter] = deviceCodeResult.DeviceCode, + [OAuth2Constants.ClientIdParameter] = _clientId, + }; + + TimeSpan retryInterval = deviceCodeResult.PollingInterval; + while (true) + { + ct.ThrowIfCancellationRequested(); + + try + { + using (HttpContent requestContent = new FormUrlEncodedContent(formData)) + using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent)) + using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) + { + string json = await response.Content.ReadAsStringAsync(); + + if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) + { + return result; + } + + TryDeserializeJson(json, OAuthJsonContext.Default.ErrorResponseJson, out ErrorResponseJson error); + + switch (error?.Error) + { + case OAuth2Constants.DeviceAuthorization.Errors.AuthorizationPending: + // Retry with the current polling interval value + break; + case OAuth2Constants.DeviceAuthorization.Errors.SlowDown: + // We must increase the polling interval by 5 seconds + retryInterval = retryInterval.Add(TimeSpan.FromSeconds(5)); + break; + default: + // For all other errors do not retry + throw CreateExceptionFromResponse(json); + } + } + } + catch (TimeoutException) + { + // Back-off exponentially (2 * x = x + x) + retryInterval += retryInterval; + } + + // Wait the polling interval before retrying + await Task.Delay(retryInterval, ct); + } + } + + #endregion + + #region Extension Points + + protected virtual bool TryCreateTokenEndpointResult(string json, out OAuth2TokenResult result) + { + if (TryDeserializeJson(json, + OAuthJsonContext.Default.TokenEndpointResponseJson, + out TokenEndpointResponseJson jsonObj)) + { + result = jsonObj.ToResult(); + return true; + } + + result = null; + return false; + } + + protected virtual bool TryCreateExceptionFromResponse(string json, out OAuth2Exception exception) + { + if (TryDeserializeJson(json, OAuthJsonContext.Default.ErrorResponseJson, out ErrorResponseJson obj)) + { + exception = obj.ToException(); + return true; + } + + exception = null; + return false; + } + + #endregion + + #region Helpers + + private HttpRequestMessage CreateRequestMessage(HttpMethod method, Uri requestUri, HttpContent content = null, bool addAuthHeader = false) + { + var request = new HttpRequestMessage(method, requestUri) {Content = content}; + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.Http.MimeTypeJson)); + + if (addAuthHeader && !string.IsNullOrEmpty(_clientSecret)) + { + request.AddBasicAuthenticationHeader(_clientId, _clientSecret); + } + + return request; + } + + protected Exception CreateExceptionFromResponse(string json) + { + if (TryCreateExceptionFromResponse(json, out OAuth2Exception exception)) + { + return exception; + } + + var format = "Unknown OAuth error: {0}"; + var message = string.Format(format, json); + return new OAuth2Exception(message); + } + + protected static bool TryDeserializeJson(string json, JsonTypeInfo typeInfo, out T obj) + { + try + { + obj = JsonSerializer.Deserialize(json, typeInfo); + return true; + } + catch + { + obj = default; + return false; + } + } + + #endregion + } + + public static class OAuth2ClientExtensions + { + public static Task GetAuthorizationCodeAsync( + this IOAuth2Client client, IEnumerable scopes, IOAuth2WebBrowser browser, CancellationToken ct) + { + return client.GetAuthorizationCodeAsync(scopes, browser, null, ct); + } + } +} From cdc6a4ff7ac11a2aa073184614c45435c6f96d2f Mon Sep 17 00:00:00 2001 From: Matthew John Cheetham Date: Fri, 6 Nov 2026 16:14:00 +0000 Subject: [PATCH 2/3] oauth: fix discrepancies with impl to RFC RFC 6749 states that a client MAY send client credentials (client ID + client secret) in either the `Authorization` header, or as part of the request body (such as in form data). However, the RFC also states a client MUST NOT send the client credentials in both the request body AND the `Authorization` header at the same time. We must make sure we only send credentials in the header if configured so, and therefore also only send credentials in the body if not. Additionally, depending on the implementation of the authorization server, public clients need not send a client secret either in the request body or `Authorization` header. If we have no real value, we should not send the credentials. Note that the client ID is always required, and may be present in the request body even if the credentials are sent in the `Authorization` header, so let's always still send the client ID in the body. Finally, we have also been sending the redirect URI in the request body for flows/endpoints that did not require them - stop doing that. According to RFC 6749 only the authorization code request needs a redirect URI to be sent, and also in the corresponding token request. Signed-off-by: Matthew John Cheetham --- src/Core/Authentication/OAuth/OAuth2Client.cs | 50 ++++++++++++------- .../Objects/TestOAuth2Server.cs | 5 +- 2 files changed, 36 insertions(+), 19 deletions(-) diff --git a/src/Core/Authentication/OAuth/OAuth2Client.cs b/src/Core/Authentication/OAuth/OAuth2Client.cs index d9bf96a5c..b392bf038 100644 --- a/src/Core/Authentication/OAuth/OAuth2Client.cs +++ b/src/Core/Authentication/OAuth/OAuth2Client.cs @@ -211,10 +211,9 @@ public async Task GetDeviceCodeAsync(IEnumerable string scopesStr = string.Join(" ", scopes); - var formData = new Dictionary - { - [OAuth2Constants.ClientIdParameter] = _clientId - }; + var formData = new Dictionary(); + + AddClientParams(formData); if (!string.IsNullOrWhiteSpace(scopesStr)) { @@ -245,10 +244,10 @@ public async Task GetTokenByAuthorizationCodeAsync(OAuth2Auth [OAuth2Constants.TokenEndpoint.GrantTypeParameter] = OAuth2Constants.TokenEndpoint.AuthorizationCodeGrantType, [OAuth2Constants.TokenEndpoint.AuthorizationCodeParameter] = authorizationCodeResult.Code, [OAuth2Constants.TokenEndpoint.PkceVerifierParameter] = authorizationCodeResult.CodeVerifier, - [OAuth2Constants.ClientIdParameter] = _clientId, - [OAuth2Constants.ClientSecretParameter] = _clientSecret }; + AddClientParams(formData); + if (authorizationCodeResult.RedirectUri != null) { formData[OAuth2Constants.RedirectUriParameter] = authorizationCodeResult.RedirectUri.OriginalString; @@ -260,7 +259,7 @@ public async Task GetTokenByAuthorizationCodeAsync(OAuth2Auth } using (HttpContent requestContent = new FormUrlEncodedContent(formData)) - using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent, _addAuthHeader)) + using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent)) using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) { string json = await response.Content.ReadAsStringAsync(); @@ -282,17 +281,12 @@ public async Task GetTokenByRefreshTokenAsync(string refreshT { [OAuth2Constants.TokenEndpoint.GrantTypeParameter] = OAuth2Constants.TokenEndpoint.RefreshTokenGrantType, [OAuth2Constants.TokenEndpoint.RefreshTokenParameter] = refreshToken, - [OAuth2Constants.ClientIdParameter] = _clientId, - [OAuth2Constants.ClientSecretParameter] = _clientSecret }; - if (_redirectUri != null) - { - formData[OAuth2Constants.RedirectUriParameter] = _redirectUri.ToString(); - } + AddClientParams(formData); using (HttpContent requestContent = new FormUrlEncodedContent(formData)) - using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent, _addAuthHeader)) + using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent)) using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) { string json = await response.Content.ReadAsStringAsync(); @@ -314,9 +308,10 @@ public async Task GetTokenByDeviceCodeAsync(OAuth2DeviceCodeR { [OAuth2Constants.DeviceAuthorization.GrantTypeParameter] = OAuth2Constants.DeviceAuthorization.DeviceCodeGrantType, [OAuth2Constants.DeviceAuthorization.DeviceCodeParameter] = deviceCodeResult.DeviceCode, - [OAuth2Constants.ClientIdParameter] = _clientId, }; + AddClientParams(formData); + TimeSpan retryInterval = deviceCodeResult.PollingInterval; while (true) { @@ -397,12 +392,33 @@ protected virtual bool TryCreateExceptionFromResponse(string json, out OAuth2Exc #region Helpers - private HttpRequestMessage CreateRequestMessage(HttpMethod method, Uri requestUri, HttpContent content = null, bool addAuthHeader = false) + private void AddClientParams(Dictionary data) + { + // RFC 6749, Sections 2.2 and 3.2.1: client_id is identification, not + // authentication, and MAY be sent in the body alongside HTTP Basic. + // Including it also satisfies unauthenticated authorization-code requests + // and device requests (RFC 8628, Sections 3.1 and 3.4). + data[OAuth2Constants.ClientIdParameter] = _clientId; + + // RFC 6749, Section 2.3: clients MUST NOT use multiple authentication + // methods per request. Section 2.3.1 allows request-body password + // authentication when supported by the server, and permits omission + // of an empty client_secret. + if (!_addAuthHeader && !string.IsNullOrEmpty(_clientSecret)) + { + data[OAuth2Constants.ClientSecretParameter] = _clientSecret; + } + } + + private HttpRequestMessage CreateRequestMessage(HttpMethod method, Uri requestUri, HttpContent content = null) { var request = new HttpRequestMessage(method, requestUri) {Content = content}; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.Http.MimeTypeJson)); - if (addAuthHeader && !string.IsNullOrEmpty(_clientSecret)) + // RFC 6749, Section 2.3.1: servers MUST support HTTP Basic for clients + // issued a password. Select it instead of body password authentication + // to satisfy the single-method requirement in Section 2.3. + if (_addAuthHeader && !string.IsNullOrEmpty(_clientSecret)) { request.AddBasicAuthenticationHeader(_clientId, _clientSecret); } diff --git a/src/TestInfrastructure/Objects/TestOAuth2Server.cs b/src/TestInfrastructure/Objects/TestOAuth2Server.cs index f1188e172..773dea06b 100644 --- a/src/TestInfrastructure/Objects/TestOAuth2Server.cs +++ b/src/TestInfrastructure/Objects/TestOAuth2Server.cs @@ -199,6 +199,9 @@ private async Task OnTokenEndpointAsync(HttpRequestMessage } formData.TryGetValue(OAuth2Constants.TokenEndpoint.PkceVerifierParameter, out string codeVerifier); + + // If the authorization code grant was created with a redirect URI then the exact same redirect URI + // MUST be used for the token request per RFC 6749 section 4.1.3. if (formData.TryGetValue(OAuth2Constants.RedirectUriParameter, out string redirectUriStr)) { app.ValidateRedirect(redirectUriStr); @@ -213,8 +216,6 @@ private async Task OnTokenEndpointAsync(HttpRequestMessage throw new Exception("Missing refresh token parameter"); } - app.ValidateRedirect(formData[OAuth2Constants.RedirectUriParameter]); - tokenResp = app.CreateTokenByRefreshTokenGrant(TokenGenerator, refreshToken); } else if (StringComparer.OrdinalIgnoreCase.Equals(grantType, OAuth2Constants.DeviceAuthorization.DeviceCodeGrantType)) From c550bbd0ed643efbe669a8f404d0f719a38cc610 Mon Sep 17 00:00:00 2001 From: Matthew John Cheetham Date: Fri, 6 Nov 2026 16:14:00 +0000 Subject: [PATCH 3/3] oauth: pass cancellation token to body read operation We have a cancellation token from the caller, but we have not been passing this down to the `Content.ReadAdStringAsync()` operation on the HTTP responses. Let's do this. Signed-off-by: Matthew John Cheetham --- src/Core/Authentication/OAuth/OAuth2Client.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Core/Authentication/OAuth/OAuth2Client.cs b/src/Core/Authentication/OAuth/OAuth2Client.cs index b392bf038..bb52e53bd 100644 --- a/src/Core/Authentication/OAuth/OAuth2Client.cs +++ b/src/Core/Authentication/OAuth/OAuth2Client.cs @@ -224,7 +224,7 @@ public async Task GetDeviceCodeAsync(IEnumerable using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.DeviceAuthorizationEndpoint, requestContent)) using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) { - string json = await response.Content.ReadAsStringAsync(); + string json = await response.Content.ReadAsStringAsync(ct); if (response.IsSuccessStatusCode && TryDeserializeJson(json, OAuthJsonContext.Default.DeviceAuthorizationEndpointResponseJson, out DeviceAuthorizationEndpointResponseJson jsonObj)) { @@ -262,7 +262,7 @@ public async Task GetTokenByAuthorizationCodeAsync(OAuth2Auth using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent)) using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) { - string json = await response.Content.ReadAsStringAsync(); + string json = await response.Content.ReadAsStringAsync(ct); if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) { @@ -289,7 +289,7 @@ public async Task GetTokenByRefreshTokenAsync(string refreshT using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent)) using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) { - string json = await response.Content.ReadAsStringAsync(); + string json = await response.Content.ReadAsStringAsync(ct); if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) { @@ -323,7 +323,7 @@ public async Task GetTokenByDeviceCodeAsync(OAuth2DeviceCodeR using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, _endpoints.TokenEndpoint, requestContent)) using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) { - string json = await response.Content.ReadAsStringAsync(); + string json = await response.Content.ReadAsStringAsync(ct); if (response.IsSuccessStatusCode && TryCreateTokenEndpointResult(json, out OAuth2TokenResult result)) {