Created
September 5, 2012 13:57
-
-
Save benfoster/3636956 to your computer and use it in GitHub Desktop.
Api Key authentication handler
This file contains hidden or 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
| 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); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You will probably change that when you put this in your app but you reach out to the
Resultof theTaskobject before checking status of it. The operation might have been faulted or cancelled.