Skip to content

Commit

Permalink
OAuthHandler: Retry with new access token on HTTP 401
Browse files Browse the repository at this point in the history
  • Loading branch information
bastianeicher committed Mar 23, 2020
1 parent fa08376 commit 8a1eb1e
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions src/TypedRest.OAuth/Http/OAuthHandler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
Expand Down Expand Up @@ -38,13 +39,19 @@ public OAuthHandler(OAuthOptions oAuthOptions, HttpMessageHandler? innerHandler
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_accessToken == null || _accessToken.IsExpired)
_accessToken = await RequestAccessTokenAsync(cancellationToken);
await RequestAccessTokenAsync(cancellationToken);

request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken.Value);
return await base.SendAsync(request, cancellationToken).NoContext();
var response = await SendAuthenticatedAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
// Retry with new access token
await RequestAccessTokenAsync(cancellationToken);
return await SendAuthenticatedAsync(request, cancellationToken);
}
else return response;
}

private async Task<AccessToken> RequestAccessTokenAsync(CancellationToken cancellationToken)
private async Task RequestAccessTokenAsync(CancellationToken cancellationToken)
{
var request = new ClientCredentialsTokenRequest
{
Expand All @@ -60,7 +67,7 @@ private async Task<AccessToken> RequestAccessTokenAsync(CancellationToken cancel

if (response.Exception != null) throw response.Exception;
if (response.IsError) throw new AuthenticationException(response.Error);
return new AccessToken(
_accessToken = new AccessToken(
response.AccessToken,
DateTime.Now.AddSeconds(response.ExpiresIn - 15 /* buffer time */));
}
Expand All @@ -73,5 +80,11 @@ private async Task<string> DiscoverTokenEndpointAsync(CancellationToken cancella
if (response.IsError) throw new AuthenticationException(response.Error);
return response.TokenEndpoint;
}

private async Task<HttpResponseMessage> SendAuthenticatedAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken!.Value);
return await base.SendAsync(request, cancellationToken).NoContext();
}
}
}

0 comments on commit 8a1eb1e

Please sign in to comment.