-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathOAuth2Client.cs
More file actions
253 lines (208 loc) · 9.48 KB
/
Copy pathOAuth2Client.cs
File metadata and controls
253 lines (208 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
using OpenFga.Sdk.Client.Model;
using OpenFga.Sdk.Configuration;
using OpenFga.Sdk.Constants;
using OpenFga.Sdk.Exceptions;
using OpenFga.Sdk.Telemetry;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
namespace OpenFga.Sdk.ApiClient;
/// <summary>
/// OAuth2 Client to exchange the credentials for an access token using the client credentials flow
/// </summary>
public class OAuth2Client {
private const int TOKEN_EXPIRY_BUFFER_THRESHOLD_IN_SEC = FgaConstants.TokenExpiryThresholdBufferInSec;
private const int
TOKEN_EXPIRY_JITTER_IN_SEC = FgaConstants.TokenExpiryJitterInSec; // We add some jitter so that token refreshes are less likely to collide
private const string DEFAULT_API_TOKEN_ISSUER_PATH = "/oauth/token";
private static readonly Random _random = new();
private static readonly object _randomLock = new();
private readonly Metrics metrics;
/// <summary>
/// Credentials Flow Response
/// https://auth0.com/docs/get-started/authentication-and-authorization-flow/client-credentials-flow
/// </summary>
public class AccessTokenResponse {
/// <summary>
/// Time period after which the token will expire (in ms)
/// </summary>
[JsonPropertyName("expires_in")]
public long ExpiresIn { get; set; }
/// <summary>
/// Token Type
/// </summary>
[JsonPropertyName("token_type")]
public string? TokenType { get; set; }
/// <summary>
/// Access token to use
/// </summary>
[JsonPropertyName("access_token")]
public string? AccessToken { get; set; }
}
private class AuthToken {
public DateTime? ExpiresAt { get; set; }
public string? AccessToken { get; set; }
public bool IsValid() {
if (string.IsNullOrWhiteSpace(AccessToken)) {
return false;
}
if (ExpiresAt == null) {
return true;
}
int jitter;
lock (_randomLock) {
jitter = _random.Next(0, TOKEN_EXPIRY_JITTER_IN_SEC);
}
return ExpiresAt - DateTime.Now >
TimeSpan.FromSeconds(TOKEN_EXPIRY_BUFFER_THRESHOLD_IN_SEC + jitter);
}
}
#region Fields
private readonly BaseClient _httpClient;
private AuthToken _authToken = new();
private readonly object _exchangeLock = new();
private Task<string>? _inflightExchange;
private IDictionary<string, string> _authRequest { get; }
private string _apiTokenIssuer { get; }
private readonly RetryHandler _retryHandler;
#endregion
#region Methods
/// <summary>
/// Initializes a new instance of the <see cref="OAuth2Client" /> class
/// </summary>
/// <param name="credentialsConfig"></param>
/// <param name="httpClient"></param>
/// <param name="retryParams"></param>
/// <param name="metrics"></param>
/// <exception cref="NullReferenceException"></exception>
public OAuth2Client(Credentials credentialsConfig, BaseClient httpClient, RetryParams retryParams,
Metrics metrics) {
if (credentialsConfig == null) {
throw new Exception("Credentials are required for OAuth2Client");
}
if (string.IsNullOrWhiteSpace(credentialsConfig.Config!.ClientId)) {
throw new FgaRequiredParamError("OAuth2Client", "config.ClientId");
}
if (string.IsNullOrWhiteSpace(credentialsConfig.Config.ClientSecret)) {
throw new FgaRequiredParamError("OAuth2Client", "config.ClientSecret");
}
string? normalizedApiTokenIssuer = ApiTokenIssuerNormalizer.Normalize(credentialsConfig.Config.ApiTokenIssuer);
if (string.IsNullOrWhiteSpace(normalizedApiTokenIssuer)) {
throw new FgaRequiredParamError("OAuth2Client", "config.ApiTokenIssuer");
}
_httpClient = httpClient;
var normalizedApiTokenIssuerUri = new Uri(normalizedApiTokenIssuer, UriKind.Absolute);
var normalizedApiTokenIssuerUriWithPath = string.IsNullOrWhiteSpace(normalizedApiTokenIssuerUri.AbsolutePath) || normalizedApiTokenIssuerUri.AbsolutePath.Equals("/")
? new Uri(normalizedApiTokenIssuerUri, DEFAULT_API_TOKEN_ISSUER_PATH)
: normalizedApiTokenIssuerUri;
_apiTokenIssuer = normalizedApiTokenIssuerUriWithPath.ToString();
_authRequest = new Dictionary<string, string> {
{ "client_id", credentialsConfig.Config.ClientId },
{ "client_secret", credentialsConfig.Config.ClientSecret },
{ "grant_type", "client_credentials" }
};
if (!string.IsNullOrWhiteSpace(credentialsConfig.Config.ApiAudience)) {
_authRequest["audience"] = credentialsConfig.Config.ApiAudience;
}
if (!string.IsNullOrWhiteSpace(credentialsConfig.Config.Scopes)) {
_authRequest["scope"] = credentialsConfig.Config.Scopes;
}
_retryHandler = new RetryHandler(retryParams);
this.metrics = metrics;
}
/// <summary>
/// Exchange client id and client secret for an access token, and handles token refresh
/// </summary>
/// <exception cref="NullReferenceException"></exception>
/// <exception cref="Exception"></exception>
private async Task ExchangeTokenAsync(CancellationToken cancellationToken = default) {
var requestBuilder = new RequestBuilder<IDictionary<string, string>> {
Method = HttpMethod.Post,
BasePath = _apiTokenIssuer,
PathTemplate = "",
Body = _authRequest,
ContentType = "application/x-www-form-urlencode"
};
var sw = Stopwatch.StartNew();
var accessTokenResponse = await Retry(async (attemptCount) =>
await _httpClient.SendRequestAsync<IDictionary<string, string>, AccessTokenResponse>(
requestBuilder,
null,
"ExchangeTokenAsync",
attemptCount,
cancellationToken),
cancellationToken);
sw.Stop();
metrics.BuildForClientCredentialsResponse(accessTokenResponse.rawResponse, requestBuilder,
sw, accessTokenResponse.retryCount);
_authToken = new AuthToken { AccessToken = accessTokenResponse.responseContent?.AccessToken };
if (accessTokenResponse.responseContent?.ExpiresIn != null) {
_authToken.ExpiresAt = DateTime.Now + TimeSpan.FromSeconds(accessTokenResponse.responseContent.ExpiresIn);
}
}
private async Task<TResult> Retry<TResult>(Func<int, Task<TResult>> retryable, CancellationToken cancellationToken = default) {
var attemptCount = 0; // 0 = initial request, 1+ = retry attempts
while (true) {
try {
return await retryable(attemptCount).ConfigureAwait(false);
}
catch (FgaApiError err) when (err is FgaApiRateLimitExceededError || err.ShouldRetry) {
// Check if we should retry based on status code and attempt count
if (!_retryHandler.ShouldRetry(err.StatusCode, attemptCount)) {
err.RetryAttempt = attemptCount;
if (err.ResponseHeaders != null) {
var info = _retryHandler.ExtractRetryAfterInfoFromHeaders(err.ResponseHeaders);
err.RetryAfter = info.retryAfterSeconds;
err.RetryAfterRaw = info.retryAfterRaw;
}
throw;
}
// Calculate delay using Retry-After header or exponential backoff
var delay = _retryHandler.CalculateDelayFromHeaders(err.ResponseHeaders, attemptCount);
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
attemptCount++;
}
catch (Exception ex) when (_retryHandler.IsTransientError(ex, attemptCount)) {
// Network error - retry with exponential backoff (no headers available)
var delay = _retryHandler.CalculateDelayFromHeaders(null, attemptCount);
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
attemptCount++;
}
}
}
/// <summary>
/// Gets the access token, and handles exchanging, rudimentary in memory caching and refreshing it when expired
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public Task<string> GetAccessTokenAsync(CancellationToken cancellationToken = default) {
if (_authToken.IsValid()) {
return Task.FromResult(_authToken.AccessToken!);
}
lock (_exchangeLock) {
if (_authToken.IsValid()) {
return Task.FromResult(_authToken.AccessToken!);
}
_inflightExchange ??= ExchangeAndResetAsync(cancellationToken);
return _inflightExchange;
}
}
private async Task<string> ExchangeAndResetAsync(CancellationToken cancellationToken) {
try {
await Task.Yield();
await ExchangeTokenAsync(cancellationToken).ConfigureAwait(false);
return _authToken.AccessToken ?? throw new InvalidOperationException();
}
finally {
lock (_exchangeLock) {
_inflightExchange = null;
}
}
}
#endregion
}