|
| 1 | +using System.Net.Http; |
| 2 | +using System.Text.Json; |
| 3 | +using AdaptiveRemote.Logging; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using Microsoft.Extensions.Options; |
| 6 | + |
| 7 | +namespace AdaptiveRemote.Services.Backend; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Acquires and caches OAuth2 access tokens from AWS Cognito using the |
| 11 | +/// Client Credentials flow. Token refresh is lazy: the cached token is |
| 12 | +/// returned until it is within <see cref="ExpiryBuffer"/> of expiring, |
| 13 | +/// at which point a new token is acquired. |
| 14 | +/// </summary> |
| 15 | +internal sealed class CognitoTokenService : ICognitoTokenService, IDisposable |
| 16 | +{ |
| 17 | + // Refresh the token this many seconds before it actually expires. |
| 18 | + private static readonly TimeSpan ExpiryBuffer = TimeSpan.FromSeconds(60); |
| 19 | + |
| 20 | + private readonly BackendSettings _settings; |
| 21 | + private readonly HttpClient _httpClient; |
| 22 | + private readonly MessageLogger _log; |
| 23 | + |
| 24 | + private string? _cachedToken; |
| 25 | + private DateTimeOffset _tokenExpiry = DateTimeOffset.MinValue; |
| 26 | + private string? _tokenEndpoint; |
| 27 | + private readonly SemaphoreSlim _lock = new(1, 1); |
| 28 | + |
| 29 | + public CognitoTokenService( |
| 30 | + IOptions<BackendSettings> settings, |
| 31 | + ILogger<CognitoTokenService> logger) |
| 32 | + { |
| 33 | + _settings = settings.Value; |
| 34 | + _httpClient = new HttpClient(); |
| 35 | + _log = new MessageLogger(logger); |
| 36 | + } |
| 37 | + |
| 38 | + public async Task<string> GetAccessTokenAsync(CancellationToken cancellationToken) |
| 39 | + { |
| 40 | + await _lock.WaitAsync(cancellationToken); |
| 41 | + try |
| 42 | + { |
| 43 | + if (_cachedToken is not null && DateTimeOffset.UtcNow < _tokenExpiry - ExpiryBuffer) |
| 44 | + { |
| 45 | + return _cachedToken; |
| 46 | + } |
| 47 | + |
| 48 | + _log.CognitoTokenService_AcquiringToken(); |
| 49 | + try |
| 50 | + { |
| 51 | + string endpoint = await GetTokenEndpointAsync(cancellationToken); |
| 52 | + (_cachedToken, _tokenExpiry) = await AcquireTokenAsync(endpoint, cancellationToken); |
| 53 | + _log.CognitoTokenService_TokenAcquired(); |
| 54 | + return _cachedToken; |
| 55 | + } |
| 56 | + catch (Exception ex) |
| 57 | + { |
| 58 | + _log.CognitoTokenService_AcquireTokenFailed(ex); |
| 59 | + throw; |
| 60 | + } |
| 61 | + } |
| 62 | + finally |
| 63 | + { |
| 64 | + _lock.Release(); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private async Task<string> GetTokenEndpointAsync(CancellationToken cancellationToken) |
| 69 | + { |
| 70 | + if (_tokenEndpoint is not null) |
| 71 | + { |
| 72 | + return _tokenEndpoint; |
| 73 | + } |
| 74 | + |
| 75 | + CognitoClientSettings cognito = _settings.Cognito; |
| 76 | + string discoveryUrl = $"{cognito.Authority.TrimEnd('/')}/.well-known/openid-configuration"; |
| 77 | + |
| 78 | + using HttpResponseMessage discoveryResponse = |
| 79 | + await _httpClient.GetAsync(discoveryUrl, cancellationToken); |
| 80 | + |
| 81 | + discoveryResponse.EnsureSuccessStatusCode(); |
| 82 | + |
| 83 | + string json = await discoveryResponse.Content.ReadAsStringAsync(cancellationToken); |
| 84 | + using JsonDocument doc = JsonDocument.Parse(json); |
| 85 | + _tokenEndpoint = doc.RootElement.GetProperty("token_endpoint").GetString() |
| 86 | + ?? throw new InvalidOperationException( |
| 87 | + "token_endpoint not found in OIDC discovery document"); |
| 88 | + |
| 89 | + return _tokenEndpoint; |
| 90 | + } |
| 91 | + |
| 92 | + private async Task<(string Token, DateTimeOffset Expiry)> AcquireTokenAsync( |
| 93 | + string endpoint, |
| 94 | + CancellationToken cancellationToken) |
| 95 | + { |
| 96 | + CognitoClientSettings cognito = _settings.Cognito; |
| 97 | + |
| 98 | + List<KeyValuePair<string, string>> parameters = |
| 99 | + [ |
| 100 | + new("grant_type", "client_credentials"), |
| 101 | + new("client_id", cognito.ClientId), |
| 102 | + new("client_secret", cognito.ClientSecret), |
| 103 | + ]; |
| 104 | + |
| 105 | + if (!string.IsNullOrEmpty(cognito.Scope)) |
| 106 | + { |
| 107 | + parameters.Add(new("scope", cognito.Scope)); |
| 108 | + } |
| 109 | + |
| 110 | + using FormUrlEncodedContent content = new(parameters); |
| 111 | + using HttpResponseMessage response = |
| 112 | + await _httpClient.PostAsync(endpoint, content, cancellationToken); |
| 113 | + |
| 114 | + response.EnsureSuccessStatusCode(); |
| 115 | + |
| 116 | + string json = await response.Content.ReadAsStringAsync(cancellationToken); |
| 117 | + using JsonDocument doc = JsonDocument.Parse(json); |
| 118 | + |
| 119 | + string accessToken = doc.RootElement.GetProperty("access_token").GetString() |
| 120 | + ?? throw new InvalidOperationException("access_token not found in token response"); |
| 121 | + |
| 122 | + int expiresIn = doc.RootElement.TryGetProperty("expires_in", out JsonElement expiresInElement) |
| 123 | + ? expiresInElement.GetInt32() |
| 124 | + : 3600; |
| 125 | + |
| 126 | + return (accessToken, DateTimeOffset.UtcNow.AddSeconds(expiresIn)); |
| 127 | + } |
| 128 | + |
| 129 | + public void Dispose() |
| 130 | + { |
| 131 | + _httpClient.Dispose(); |
| 132 | + _lock.Dispose(); |
| 133 | + } |
| 134 | +} |
0 commit comments