Created
December 10, 2014 20:24
-
-
Save clairernovotny/b8b16841a5c5dcf6834b to your computer and use it in GitHub Desktop.
Authenticating handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AuthenticatedHttpClientHandler : HttpClientHandler | |
{ | |
private readonly Func<Task<string>> getToken; | |
public AuthenticatedHttpClientHandler(Func<Task<string>> getToken) | |
{ | |
if (getToken == null) throw new ArgumentNullException("getToken"); | |
this.getToken = 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().ConfigureAwait(false); | |
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token); | |
} | |
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment