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.
In addition, I added the API key as an appSetting value to my web.config file:
<configuration> <!-- ... --> <appSettings> <!-- ... --> <add key="BasicAuthAPIKey" value="<password>"/> </appSettings> <!-- ... -->
Then put the [TokenAuthorize] attribute on any controller which needs authorization. E.g.
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.