-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathAuthenticatedMessageHandler.cs
More file actions
49 lines (43 loc) · 1.81 KB
/
AuthenticatedMessageHandler.cs
File metadata and controls
49 lines (43 loc) · 1.81 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
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using Flurl.Http.Configuration;
namespace OpenStack.Authentication
{
/// <summary>
/// Used by Flurl for all requests. Understands how to authenticate and retry when a token expires.
/// </summary>
/// <exclude />
internal class AuthenticatedMessageHandler : FlurlMessageHandler
{
public AuthenticatedMessageHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{ }
public IAuthenticationProvider AuthenticationProvider;
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if(AuthenticationProvider == null)
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
string token = await AuthenticationProvider.GetToken(cancellationToken).ConfigureAwait(false);
request.Headers.SetAuthToken(token);
try
{
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
// var contentStr = await response.Content.ReadAsStringAsync();
return response;
}
catch (FlurlHttpException ex)
{
if (ex.Call.HttpStatus != HttpStatusCode.Unauthorized)
throw;
}
// Retry with a new token
var retryRequest = request.Copy();
var retryToken = await AuthenticationProvider.GetToken(cancellationToken).ConfigureAwait(false);
retryRequest.Headers.SetAuthToken(retryToken);
return await base.SendAsync(retryRequest, cancellationToken).ConfigureAwait(false);
}
}
}