forked from reactiveui/refit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthenticatedHttpClientHandler.cs
35 lines (31 loc) · 1.21 KB
/
AuthenticatedHttpClientHandler.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
using System.Net.Http;
using System.Net.Http.Headers;
namespace Refit
{
class AuthenticatedHttpClientHandler : DelegatingHandler
{
readonly Func<HttpRequestMessage, CancellationToken, Task<string>> getToken;
public AuthenticatedHttpClientHandler(
Func<HttpRequestMessage, CancellationToken, Task<string>> getToken,
HttpMessageHandler? innerHandler = null
)
: base(innerHandler ?? new HttpClientHandler())
{
this.getToken = getToken ?? throw new ArgumentNullException(nameof(getToken));
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken
)
{
// See if the request has an authorize header
var auth = request.Headers.Authorization;
if (auth != null)
{
var token = await getToken(request, cancellationToken).ConfigureAwait(false);
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
}