Search code examples
asp.net-web-apioauthowinasp.net-identity-2

API Keys in addition to OAuth OWIN/Web Api


I have an interesting scenario that I am looking to get some guidance on.

I have currently implemented OAuth using the standard OWIN functionality with Web API and ASP.NET Identity. Have also successfully implemented the Client Credentials functionality that allows clients (like Browsers and iPhones) to perform API access for anonymous mode of operations until a RO login occurs.

We now have a scenario where we want to build a javascript (JSONP) widget similar to that of Stripe Checkout (https://stripe.com/docs/checkout). As you will see, this widget can be embedded pretty easily by providing a simple data-key attribute as a part of the script tag. My assumption is that this is created in the back-end as a simple API Key but in addition to a list of registered domains that it can be called from. When this key is passed to the API, the api validates it against the domain the request was made from to ensure that API can access the necessary resources granted to the key.

My questions are:

  1. How can I implement the API Key in addition to OAuth Bearer tokens in the OWIN pipeline? All the documentation that I see usually suggests writing a separate delegate handler for looking up Keys etc. but wouldn't my OWIN pipeline even make it that far because the call to the action itself is not authorized?

  2. We also explicitly remove any other authentication other than OAuth in the following lines of code:

    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
  3. Is there an easier way to validate clients with just the client Id (without secrets) for javascript modes as storing secrets is nearly impossible in js environments?

  4. Am I missing something obvious that I could do to simplify this process?

I guess we've figured out everything in terms of creating the JSONP widget, but this part has left me a little confused.

Any help would be very appreciated!


Solution

  • As Owin is a pipeline, all authentication middlewares are executed on each request. In your example, a request might come in with an API key in the header: the first authentication middleware might be your oauth/bearer authentication - if no relevant header is present, no identity will be attached to the request by that piece of middleware and the request continues along the pipeline. The next middleware could be some API key authentication middleware (you can find an implementation here: https://github.com/jamesharling/Microsoft.Owin.Security.ApiKey), which will detect your API key header and attach the relevant identity to the request.