Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created September 5, 2012 13:57
Show Gist options
  • Select an option

  • Save benfoster/3636956 to your computer and use it in GitHub Desktop.

Select an option

Save benfoster/3636956 to your computer and use it in GitHub Desktop.
Api Key authentication handler
public class ApiKeyAuthHandler : DelegatingHandler
{
private const string ApiKeySchemeName = "ApiKey";
private const string AuthResponseHeader = "WWW-Authenticate";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var authHeader = request.Headers.Authorization;
if (authHeader != null && authHeader.Scheme == ApiKeySchemeName)
{
var principal = ValidateApiKey(authHeader.Parameter);
if (principal != null)
{
Thread.CurrentPrincipal = principal;
}
}
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if (response.StatusCode == HttpStatusCode.Unauthorized && !response.Headers.Contains(AuthResponseHeader))
{
response.Headers.Add(AuthResponseHeader, ApiKeySchemeName);
}
return response;
});
}
IPrincipal ValidateApiKey(string authParameter)
{
if (authParameter.IsNullOrEmpty() || authParameter != "1234-5678")
{
return null;
}
return new GenericPrincipal(new GenericIdentity("Test User", ApiKeySchemeName), null);
}
}
@tugberkugurlu
Copy link

You will probably change that when you put this in your app but you reach out to the Result of the Task object before checking status of it. The operation might have been faulted or cancelled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment