Skip to content

Instantly share code, notes, and snippets.

@andy51002000
Last active October 22, 2019 03:54
Show Gist options
  • Save andy51002000/5da56972cb73472a185cb87d15a6378e to your computer and use it in GitHub Desktop.
Save andy51002000/5da56972cb73472a185cb87d15a6378e to your computer and use it in GitHub Desktop.
API Key Message handler to protect the REST API Endpoint
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