diff --git a/src/Core/Authentication/OAuth/OAuth2Client.cs b/src/Core/Authentication/OAuth/OAuth2Client.cs index 1089fae1d..bb52e53bd 100644 --- a/src/Core/Authentication/OAuth/OAuth2Client.cs +++ b/src/Core/Authentication/OAuth/OAuth2Client.cs @@ -1,450 +1,466 @@ -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(); + + AddClientParams(formData); + + 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(ct); + + 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, + }; + + AddClientParams(formData); + + 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)) + using (HttpResponseMessage response = await _httpClient.SendAsync(request, ct)) + { + string json = await response.Content.ReadAsStringAsync(ct); + + 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, + }; + + AddClientParams(formData); + + 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(ct); + + 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, + }; + + AddClientParams(formData); + + 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(ct); + + 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 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)); + + // 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); + } + + 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); + } + } +} 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))