Last active
October 16, 2017 07:42
-
-
Save code-atom/138eca7659aeb80d5337cc8a050d5d77 to your computer and use it in GitHub Desktop.
Api key verify 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
/// <summary> | |
/// Verify that all request to api must contain apikey | |
/// </summary> | |
public class APIKeyHandler : DelegatingHandler | |
{ | |
private string APIToken = "apiKey"; | |
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) | |
{ | |
if (request.Method == HttpMethod.Options) goto success; | |
var apiKey = request.GetQueryString(APIToken); | |
if (!string.IsNullOrEmpty(apiKey)) goto verifyKey; | |
IEnumerable<string> availableHeaders = null; | |
if (!request.Headers.TryGetValues(APIToken, out availableHeaders)) | |
return request.ApiKeyMissingExpetion(); | |
if (availableHeaders.Count() > 1) | |
return request.MulitpleKeyProvideException(); | |
apiKey = availableHeaders.First(); | |
verifyKey: | |
if (!Config.APIKEYS.ContainsKey(apiKey)) | |
return request.InvalidApikeyException(); | |
var deviceType = Config.APIKEYS[apiKey]; | |
var secretKey = Config.APIKEYSECRET[apiKey]; | |
request.Headers.Add("DeviceType", deviceType); | |
request.Headers.Add("secret", secretKey); | |
success: | |
return base.SendAsync(request, cancellationToken); | |
} | |
} |
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 static class WebApiConfig | |
{ | |
public static void Register(HttpConfiguration config) | |
{ | |
#region Global Handler | |
config.MessageHandlers.Add(new APIKeyHandler()); | |
#endregion Global Handler | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment