This is a good starter bit on how to lockdown inbound request messages to restful wcf services. One caveat, is that this article has nothing to do with message security. This article only shows how to hook into WCF to verify that a message contains a special value... aka "API Key". If the special value is not valid, the message is denied.
The sample provided here has helped me get started with some basic message security. I plan on using this sample as a spring board to verify that messages were signed with a shared secret.
When I try to use this approach on my application where I have helpEnabled=true on the endpoint, it enforces API keys to be present on help page requests. How can I avoid this? I.e. I would not want the user to be required to add an API key to view the help pages.
Try this
private bool IsHelpPage(Message requestMessage)
{
return requestMessage.Headers.To.AbsolutePath.ToLower().EndsWith("help");
}
Then modify the check
if (this.IsHelpPage(operationContext.RequestContext.RequestMessage) || APIKeyRepository.IsValidAPIKey(key))
{
return true;
}
else
{
// Send back an HTML reply
CreateErrorReply(operationContext, key);
return false;
}
I'm not sure if this is the correct method, but this is what I did to get a WebChannelFactory working with apikey, so that I could write code like this.
WebChannelFactory<IService1> factory = new WebChannelFactory<IService1>("Service1");
IService1 service = factory.CreateChannel();
var SampleItems = service.GetCollection("bda11d91-7ade-4da1-855d-24adfe39d174");
I made a client side only Service Contract interface "IService1" and added an extra parameter to the method and uri, e.g.
[ServiceContract]
public interface IService1
{
// TODO: Implement the collection resource that will contain the SampleItem instances
[WebGet(UriTemplate = "?apikey={apikey}")]
public List<SampleItem> GetCollection(string apikey)
{
...
I don't know if this is correct, or "best practise"...
Thanks! worked like a charm. I am new to .NET world and I might be talking obvious. The API Key takes care of giving access to authorized domain. To make it more secure we can hash the domain name and generate API key which can be validated to see if the source (domain) is authorized or not. However, how will it work on mobile apps? I guess, I can create "mobile" api key and that can be used in my app and send data over ssl.
If I want to implement user based authentication like oAuth, how will that work? Do you have an example?