Last active
October 22, 2019 03:54
-
-
Save andy51002000/5da56972cb73472a185cb87d15a6378e to your computer and use it in GitHub Desktop.
API Key Message handler to protect the REST API Endpoint
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
public class APIKeyMessageHandler : DelegatingHandler | |
{ | |
private const string APIKey = "ZG95b3Vrbm93dGhhdGFjZXJpc3RoZWJlc3Rjb21wYW55aW50aGV3b3JsZGJ5YW5keQ=="; | |
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
bool validKey = false; | |
IEnumerable<string> requestHeaders; | |
var checkApiKeyExists = request.Headers.TryGetValues("MyAPIKey", out requestHeaders); | |
if (checkApiKeyExists) | |
{ | |
if (requestHeaders.FirstOrDefault().Equals(APIKey)) | |
{ | |
validKey = true; | |
} | |
} | |
if (!validKey) | |
{ | |
return new HttpResponseMessage(HttpStatusCode.Forbidden) | |
{ | |
Content = new StringContent(JsonConvert.SerializeObject(new { message = "Invalid API Key" })), | |
ReasonPhrase = "Invalid API Key" | |
}; | |
} | |
var response = await base.SendAsync(request, cancellationToken); | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment