-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDynamicBearerAuthenticatedMessageProvider.cs
155 lines (142 loc) · 7 KB
/
DynamicBearerAuthenticatedMessageProvider.cs
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
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Arcane.Framework.Sources.RestApi.Services.AuthenticatedMessageProviders.Base;
using Snd.Sdk.Tasks;
namespace Arcane.Framework.Sources.RestApi.Services.AuthenticatedMessageProviders;
/// <summary>
/// Authenticated message provider that generated dynamic bearer token header.
/// </summary>
public record DynamicBearerAuthenticatedMessageProvider : IRestApiAuthenticatedMessageProvider
{
private readonly TimeSpan expirationPeriod;
private readonly string expirationPeriodPropertyName;
private readonly HttpMethod requestMethod;
private readonly string tokenPropertyName;
private readonly string tokenRequestBody;
private readonly string tokenRequestContentType;
private readonly string authHeaderName;
private readonly string authScheme;
private readonly Uri tokenSource;
private readonly Dictionary<string, string> additionalHeaders;
private string currentToken;
private DateTimeOffset? validTo;
/// <summary>
/// Authenticated message provider that generated dynamic bearer token header.
/// </summary>
/// <param name="tokenSource">Token source address</param>
/// <param name="tokenPropertyName">Token property name</param>
/// <param name="expirationPeriodPropertyName">Token expiration property name</param>
/// <param name="requestMethod">HTTP method for token request</param>
/// <param name="tokenRequestBody">HTTP body for token request</param>
/// <param name="tokenRequestContentType">HTTP content-type header for the token request</param>
/// <param name="authHeaderName">Authorization header name</param>
/// <param name="authScheme">Authorization scheme</param>
/// <param name="additionalHeaders">Additional token headers</param>
public DynamicBearerAuthenticatedMessageProvider(string tokenSource,
string tokenPropertyName,
string expirationPeriodPropertyName,
HttpMethod requestMethod = null,
string tokenRequestBody = null,
string tokenRequestContentType = null,
Dictionary<string, string> additionalHeaders = null,
string authHeaderName = null,
string authScheme = null)
{
this.tokenSource = new Uri(tokenSource);
this.tokenPropertyName = tokenPropertyName;
this.expirationPeriodPropertyName = expirationPeriodPropertyName;
this.tokenRequestBody = tokenRequestBody;
this.tokenRequestContentType = tokenRequestContentType;
this.requestMethod = requestMethod ?? HttpMethod.Get;
this.authHeaderName = authHeaderName;
this.authScheme = authScheme;
this.additionalHeaders = additionalHeaders ?? new Dictionary<string, string>();
}
/// <summary>
/// Authenticated message provider that generated dynamic bearer token header.
/// </summary>
/// <param name="tokenSource">Token source address</param>
/// <param name="tokenPropertyName">Token property name</param>
/// <param name="expirationPeriod">Token expiration period</param>
/// <param name="requestMethod">HTTP method for token request</param>
/// <param name="tokenRequestBody">HTTP body for token request</param>
/// <param name="tokenRequestContentType">HTTP content-type header for the token request</param>
/// <param name="additionalHeaders">Additional token headers</param>
/// <param name="authHeaderName">Authorization header name</param>
/// <param name="authScheme">Authorization scheme</param>
public DynamicBearerAuthenticatedMessageProvider(string tokenSource,
string tokenPropertyName,
TimeSpan expirationPeriod,
HttpMethod requestMethod = null,
string tokenRequestBody = null,
string tokenRequestContentType = null,
Dictionary<string, string> additionalHeaders = null,
string authHeaderName = null,
string authScheme = null)
{
this.tokenSource = new Uri(tokenSource);
this.tokenPropertyName = tokenPropertyName;
this.expirationPeriod = expirationPeriod;
this.tokenRequestBody = tokenRequestBody;
this.tokenRequestContentType = tokenRequestContentType;
this.requestMethod = requestMethod ?? HttpMethod.Get;
this.authHeaderName = authHeaderName;
this.authScheme = authScheme;
this.additionalHeaders = additionalHeaders ?? new Dictionary<string, string>();
}
/// <inheritdoc cref="IRestApiAuthenticatedMessageProvider.GetAuthenticatedMessage"/>
public Task<HttpRequestMessage> GetAuthenticatedMessage(HttpClient httpClient)
{
if (this.validTo.GetValueOrDefault(DateTimeOffset.MaxValue) < DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1)))
{
return Task.FromResult(this.GetRequest());
}
var tokenHrm = new HttpRequestMessage(this.requestMethod, this.tokenSource);
if (!string.IsNullOrEmpty(tokenRequestBody))
{
tokenHrm.Content = this.tokenRequestContentType switch
{
null or "application/json" => new StringContent(tokenRequestBody, Encoding.UTF8, "application/json"),
"application/x-www-form-urlencoded" => new FormUrlEncodedContent(JsonSerializer.Deserialize<Dictionary<string, string>>(tokenRequestBody)),
_ => throw new ArgumentException($"Unsupported content type for authentication: {this.tokenRequestContentType}")
};
}
return httpClient.SendAsync(tokenHrm, CancellationToken.None).Map(response =>
{
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync();
}).FlatMap(result =>
{
var tokenResponse = JsonSerializer.Deserialize<JsonElement>(result);
this.currentToken = tokenResponse.GetProperty(this.tokenPropertyName).GetString();
this.validTo = !string.IsNullOrEmpty(expirationPeriodPropertyName)
? DateTimeOffset.UtcNow.AddSeconds(tokenResponse.GetProperty(this.expirationPeriodPropertyName).GetInt32())
: DateTimeOffset.UtcNow.Add(this.expirationPeriod);
return this.GetRequest();
});
}
private HttpRequestMessage GetRequest()
{
var request = new HttpRequestMessage();
switch (this.authHeaderName)
{
case null or "" or "Authorization":
request.Headers.Authorization = new AuthenticationHeaderValue(scheme: this.authScheme ?? "Bearer", this.currentToken);
break;
default:
request.Headers.Add(this.authHeaderName, string.IsNullOrEmpty(this.authScheme) ? this.currentToken : $"{this.authScheme} {this.currentToken}");
break;
}
foreach (var (headerKey, headerValue) in this.additionalHeaders ?? new Dictionary<string, string>())
{
request.Headers.Add(headerKey, headerValue);
}
return request;
}
}