I found scarce good examples of authorization when using .NET Web Api that I thought it would be a good idea to put up my own, in case I need it in the future. Blogging about it makes it easier to remember how it worked. Most of the examples I could find where just rehashes of the same MSDN example project.

In a project I'm currently working on I wanted to provide both user login access and an "api-key" type of access to my controllers. The following code shows how I did it. I subclassed System.Web.Http.AuthorizeAttribute and overrode the IsAuthorized-method. It looks for the Authorization header in the client request and attempts to authenticate using it. If it fails, it failovers to the original authorization scheme.

TokenAuthorize.cs (Source)

public class TokenAuthorize : AuthorizeAttribute
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("TokenAuthorize");

        public TokenAuthorize()
                : base()

        /// <summary>
        /// Safe against timing attacks.
        /// </summary>
        /// <param name="cmpAgainst"></param>
        /// <returns></returns>
        protected bool SafeCmp(String cmpAgainst)
                var password = ConfigurationManager.AppSettings["BasicAuthAPIKey"];

                if (cmpAgainst.Length != password.Length)
                        return false;

                // This loop will never short-circuit. Therefore it will always take the
                // same amount of time.
                int result = 0;
                for(int i = 0; i < cmpAgainst.Length; i++) {
                        result |= ((byte)cmpAgainst[i]) ^ ((byte)password[i]);
                return result == 0;

        protected override bool IsAuthorized(HttpActionContext httpContext)
                // Check for token in basic authentication
                var auth = httpContext.Request.Headers.Authorization;
                if(auth != null && auth.Scheme == "Basic") {
                                var nonbase64 = Convert.FromBase64String(auth.Parameter);
                                var asStr = Encoding.ASCII.GetString(nonbase64);

                                log.Debug("Authorization attempt using token: " + asStr);
                                return (SafeCmp(asStr));
                        catch (FormatException)
                                log.Debug("Invalid base64 format in auth: "+auth.Parameter);

                // Check for cookie as usual
                return base.IsAuthorized(httpContext);

In addition, I added the API key as an appSetting value to my web.config file:

        <!-- ... -->
                <!-- ... -->
                <add key="BasicAuthAPIKey" value="<password>"/>
        <!-- ... -->

Then put the [TokenAuthorize] attribute on any controller which needs authorization. E.g.

public class ProductController : ApiController
        // ....

Now you can authorize via the secret API key supplied in the Authorization header or the normal session/cookie way.

Important to note here that I overrode the System.Web.Http version and not the System.Web.Mvc version which has the same name but different method signatures. Also, for future reference it seems you should use .Http for Web Api and .Mvc for MVC controllers. Otherwise it doesn't seem to work.