I'm using an API key to "secure" my services over HTTPS and only allow access to specific IP addresses with IIS. Just override OnStartProcessingRequest()
like so:
protected override void OnStartProcessingRequest(ProcessRequestArgs Args)
{
// allow the metadata to be retrieved without specifying an API key by appending $metadata on the end
if (Args.RequestUri.Segments.Last().Replace("/", String.Empty) != "$metadata")
{
// check if a valid API key has been passed in (see Configuration.xml)
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;
// Configuration.APIKeys is just a simple list that reads from an XML file
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"); };