How to create an api key verification

Topics: Web Api
May 13, 2011 at 8:54 AM

hi guys,

I am planning to use web api on my next project. honestly, I haven't tried it yet so I am asking this question without knowing the web api system in details. I only watched couple of talks which glenn block did at mix and devdays.

We, as company, will open our product data and don't waht anybody to consume our data. So we are planning to create API key system. Structure of the system is not a problem but how can we intercept the request so that we can verify that it is legit? if it is legit, continue to work. if it is not throw an exception (but which exception, I don't know:s should I use faults here)

can our urls look like following;

actually rob jacobs has written a great blog post on this;

and also there is a project template up on the vs gallery;

I am just wondering if this thing fits in the structure of web api? (also, I am not sure, if I should use web api on my project. we will only open our data in xml and json format as I indicated an exmaple url that I would like to create)

thanks in advance.

May 13, 2011 at 6:07 PM

I am actually doing something similar, this is only some prototype code, but it seems to serve our needs.
Here is the DelegatingChannel that validates an API Key.  It is the first thing that runs on every request, and returns a  401 Unauthorized if the ApiKey isn't present/valid.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Text;

namespace WebAPIWebApp {

    public class ApiKeyVerificationChannel : DelegatingChannel {

        public ApiKeyVerificationChannel(HttpMessageChannel innerChannel)
            : base(innerChannel) {

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

            if(request.RequestUri.AbsolutePath.IndexOf("favicon.ico") >= 0)
                return Task.Factory.StartNew(() => {
                    return new HttpResponseMessage(System.Net.HttpStatusCode.NotFound, "Not Found");

            if (request.RequestUri.Segments.Length == 1 && string.IsNullOrWhiteSpace(request.RequestUri.AbsolutePath.Replace("/", ""))) {
                return base.SendAsync(request, cancellationToken);

            var apiKey = ApiKeyManager.GetKey(request);

            if(apiKey == null)
                return Task.Factory.StartNew(() => {
                    return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized, "Invalid API Key");

            return base.SendAsync(request, cancellationToken);




Then I've got some custom logic in the ApiKeyManager.GetKey method that checks for a valid key in the QueryString, Custom Header, or Authorization header.

I add it in the Global.asax file like this:

var config = (HttpHostConfiguration)HttpHostConfiguration.Create();
// Make my NewtonsoftJsonFormatter the first one so that it gets called before built in JsonFormatter
config.OperationHandlerFactory.Formatters.Insert(0, new NewtonsoftJsonFormatter());
config.OperationHandlerFactory.Formatters.Add(new JsonPFormatter());
config.AddMessageHandlers(typeof(UriFormatExtensionMessageChannel), typeof(LoggingChannel), typeof(ApiKeyVerificationChannel));

Only thing I did run across was the inability to "pass the Api Key along" with the request.  So I use the ApiKeyManager.GetKey() method to get the key again in each WebInvoke method.

Again, I've only been working with the Web Api for a couple days some I might be going about it wrong, but seems to work for us.

May 14, 2011 at 3:35 AM

Check out Pablo's post from 4/15:

May 14, 2011 at 3:42 AM

Out of curiousity, if the API key is passed using JavaScript, how would you prevent somebody from doing a "View Source" to see what the API key is and then spoofing whatever site was assigned that key?