I use the API key to "protect" my services through HTTPS and only allow access to specific IP addresses using IIS. Just override OnStartProcessingRequest()as follows:
protected override void OnStartProcessingRequest(ProcessRequestArgs Args)
{
if (Args.RequestUri.Segments.Last().Replace("/", String.Empty) != "$metadata")
{
if (!IsValidAPIKey(Args.OperationContext.RequestHeaders["APIKey"])) throw new DataServiceException("Invalid API key");
}
base.OnStartProcessingRequest(Args);
}
private bool IsValidAPIKey(string PassedAPIKey)
{
if (!String.IsNullOrEmpty(PassedAPIKey))
{
Guid APIKey;
if (Guid.TryParse(PassedAPIKey, out APIKey) && Configuration.APIKeys.Exists(x => x.Key == APIKey)) return true;
}
return false;
}
My xml file:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfAPIKey xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<APIKey Key="ee5346fa-bca5-4236-ae6c-f35ae2f69e0b" ApplicationName="blah" />
</ArrayOfAPIKey>
My client side:
base.SendingRequest += (s, e) => { e.Request.Headers.Add("APIkey", "your-api-key-here"); };