Skip to content

Instantly share code, notes, and snippets.

@clairernovotny
Created December 10, 2014 20:24
Show Gist options
  • Save clairernovotny/b8b16841a5c5dcf6834b to your computer and use it in GitHub Desktop.
Save clairernovotny/b8b16841a5c5dcf6834b to your computer and use it in GitHub Desktop.
Authenticating handler
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