forked from Kros-sk/TeaPie
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOAuth2Provider.cs
More file actions
140 lines (114 loc) · 4.82 KB
/
Copy pathOAuth2Provider.cs
File metadata and controls
140 lines (114 loc) · 4.82 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
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using TeaPie.Http.Headers;
using TeaPie.Variables;
using TeaPie.Logging.Tree;
namespace TeaPie.Http.Auth.OAuth2;
internal class OAuth2Provider(
IHttpClientFactory clientFactory,
IMemoryCache memoryCache,
ILogger<OAuth2Provider> logger,
IVariables variables)
: IAuthProvider<OAuth2Options>
{
private readonly string _accessTokenCacheKey = Guid.NewGuid() + "-access_token";
private const string RedirectUriParameterKey = "redirect_uri";
private readonly IHttpClientFactory _httpClientFactory = clientFactory;
private readonly IMemoryCache _cache = memoryCache;
private readonly ILogger<OAuth2Provider> _logger = logger;
private readonly IVariables _variables = variables;
private readonly AuthorizationHeaderHandler _authorizationHeaderHandler = new();
private OAuth2Options _configuration = new();
public async Task Authenticate(HttpRequestMessage request, CancellationToken cancellationToken)
=> _authorizationHeaderHandler.SetHeader($"Bearer {await GetToken()}", request);
public IAuthProvider<OAuth2Options> ConfigureOptions(OAuth2Options configuration)
{
_configuration = configuration;
_cache.Remove(_accessTokenCacheKey);
return this;
}
private async Task<string> GetToken()
{
var source = "cache";
var token = await _cache.GetOrCreateAsync(_accessTokenCacheKey, async _ =>
{
var newToken = await GetTokenFromRequest();
source = ResolveRequestUri();
SetVariableIfNeeded(newToken);
return newToken;
})!;
_logger.LogTrace("{Subject} was fetched from {Source}.", "Access token", source);
return token!;
}
private void SetVariableIfNeeded(string newToken)
{
if (_configuration.AccessTokenVariableName is not null)
{
_variables.SetVariable(
_configuration.AccessTokenVariableName, newToken, Constants.SecretVariableTag, Constants.NoCacheVariableTag);
}
}
private async Task<string> GetTokenFromRequest()
{
ResolveParameters(out var requestContent, out var requestUri);
using (_logger.BeginTreeScope())
{
LogSendingRequest();
var result = await SendRequest(requestContent, requestUri);
CacheToken(result);
return result.AccessToken!;
}
}
private void LogSendingRequest()
{
var body = string.Join(
Environment.NewLine, _configuration.GetParametersAsReadOnly().Select(ToStringMaskingSecrets));
_logger.LogTrace("Following HTTP request's body (www-url-encoded):{NewLine}{Body}",
Environment.NewLine,
body);
}
private static string ToStringMaskingSecrets(KeyValuePair<string, string> parameter)
=> parameter.Key.Contains("password", StringComparison.OrdinalIgnoreCase) ||
parameter.Key.Contains("secret", StringComparison.OrdinalIgnoreCase)
? $"{parameter.Key}={new string('*', parameter.Value.Length)}"
: $"{parameter.Key}={parameter.Value}";
private void ResolveParameters(out FormUrlEncodedContent requestContent, out string requestUri)
{
requestContent = new FormUrlEncodedContent(_configuration.GetParametersAsReadOnly());
requestUri = ResolveRequestUri();
}
private async Task<OAuth2TokenResponse> SendRequest(FormUrlEncodedContent requestContent, string requestUri)
{
using var client = _httpClientFactory.CreateClient(nameof(OAuth2Provider));
var response = await client.PostAsync(requestUri, requestContent);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<OAuth2TokenResponse>();
if (result is null || string.IsNullOrEmpty(result.AccessToken))
{
throw new UnauthorizedAccessException("Failed to retrieve access token.");
}
return result;
}
private void CacheToken(OAuth2TokenResponse result)
{
var cacheEntryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(result.ExpiresIn),
Priority = CacheItemPriority.High
};
_cache.Set(_accessTokenCacheKey, result.AccessToken, cacheEntryOptions);
}
private string ResolveRequestUri()
=> _configuration.HasParameter(RedirectUriParameterKey)
? _configuration.GetParameter(RedirectUriParameterKey)
: _configuration.AuthUrl;
}
internal class OAuth2TokenResponse
{
[JsonPropertyName("access_token")]
public string? AccessToken { get; set; }
[JsonPropertyName("expires_in")]
public int ExpiresIn { get; set; }
}