Securing Your API with HMAC Authentication

api / data encryption / development / security   Posted on Mar 1, 2015 by Nick Rivers

If you're building an application at some point you've probably considered writing an API to allow third parties to interact with your product. After all, unless you've been living under a rock, you know the industry has shifted to an "open web." A web that leverages and encourages creative minds to work together to extend existing software. On the other hand, you could also want to write an API that allows you replicate your application's experience on different platforms. For example, lets say you have an application on the web that tracks a user's weekly spending. But you want them to also experience this on their mobile device. You will need a secure way to authenticate a user and confirm the identity with your web server. I'm sure the term OAuth has come to mind since everyone else uses it. But do you really know when and why we use OAuth? Or does it just sound "secure" because its a familiar term?

Authentication Options

As mentioned before, many people consider OAuth for their API authentication but before you go that route, you should understand its use. OAuth is a very secure and powerful authentication system used in many popular applications like Facebook, Twitter, Instagram just to name a few. Its a library that's well maintained and uses a series of steps to validate a user's identity (called "3-legged Authorization Flow"). The biggest benefit is now third parties can leverage your software without ever exposing the user's login credentials. However if you are the owner of the application and is simply building your application on a different device, OAuth is probably overkill. You don't need to do a 3 legged authorization approach in this case. This is where HMAC comes in. There is also a 0-legged OAuth which is similar to what we will show here. HMAC is a Hash-based message authentication code. Many applications that use OAuth for third party access actually use HMAC for internally built applications. In fact, HMAC is used in OAuth during the signature process.

A Real Example

Lets look at Instagram. Instagram has a mostly readonly API but it uses OAuth for its third party API. When you sign onto "Gramgrab" (http://gramgrab.com a third party Instagram app), you see a popup window with a form to login to Instagram. Once you do this, the 3 legged auth flow begins you are redirected a few time and then you're connected. Behind the scenes a few things are happening. The simplest way to put it is:

  1. Direct user to authenticate. If they aren't logged in, they will be asked to. Then they are asked to give access to the application requesting it.
  2. The user is redirected to the third party's server where a special code is sent.
  3. The third party exchanges the code for an access token and can now make requests on the user's behalf.

But when you download the Instagram app to your phone, the experience is completely different. When logging in via the Instagram app, you type your username and password and your done. Want to guess how they are doing it?

A Helpful Analogy

Building authentication in your API can seem daunting at first but once you understand at a basic level, it will make a lot of sense. For the purpose of your understanding, we will personify the parts of your application in a fun analogy (Inspired by Dallin Noel Skinner's post on http://verisage.us/en/blog/).

So lets say everyone cooked a special item for the office potluck. Cameron baked a strawberry rhubarb pie and it was very popular with the team. Cameron wants to share his pie recipe with Annette. But they know Geoff wants to steal the recipe so they come up with a safe way to share it. Cameron mails Annette a list of ingredients and a finished pie. He leaves out one secret ingredient that only Annette and Cameron knows. Geoff knows where they both live and is able to steal the package before it reaches Annette. Geoff takes the list of ingredients and attempts to recreate the pie. But Geoff's result tasted very different from the one Cameron baked. Unfortunately for Geoff, he didn't know the secret ingredient so was unable to replicate the pie.

Cameron resends the package to Annette and this time, she receives it. She bakes the pie and compares it to the finished pie included in the package. The pies are a match so Annette can confirm she has done it correctly.

In this case, Geoff is an attacker and is unable to break in because without the secret ingredient (private key), there isn't a way to decrypt the product (hash). Or in regards of the analogy, there is no way to un-bake the pie and extract its ingredients. In a real application, Cameron is your web server, and Annette is another device or server trying to get access. The parameters (ingredients) are sent along with a signature which is a hash including the params, a timestamp and the private key (the finished pie). We use a timestamp to prevent replay attacks so each signature has a limited lifetime. Once the server receives this, it looks at the signature, generates a new signature using the parameters and the private key. If this is a match, the third party device and the web server shake hands and communicate as needed. This process is designed to never expose the private key. Needless to say, the private key should never be shared.

PHP Example

// Example class called myAPI
class myAPI {
  private function authenticate() {
    // Use parameters sent us.
    $params = $_POST['ingredients'].$_POST['timestamp'];

    // Use the private key we have stored on our server.
    $private_key = "da39a3ee5e6b4b0d3255bfef95601890afd80709";

    // Use parameters sent and private key to regenerate the hash.
    $newsignature = hash_hmac("sha1", $signature, $private_key);

    // Check for match and make sure the request was made within 30 seconds. We validate the time again during the signature process.
    if ($newsignature == $_POST['signature'] && $_POST['timestamp'] > strtotime("-30 seconds")) {
      // authentication success.
      return;
    } else {
      // authentication failed.
    }
  }
}

 

In the example above, we are using HMAC to generate a hash the same way the third party device did so if we do things right, we should have a matching signature.

I know this was quite a bit to take in but I hope the images and analogy made it easier to grasp. This was a pretty general overview of HMAC auth but if you have any further questions, feel free to tweet us @Blueprinttweets and I will do my best to help. We work with APIs quite a bit so if you need our services, feel free to tweet us or drop us a line at http://blueprintinteractive.com/contact!

Search the Blog

Blueprint Tweets

Blueprint is proud to help flip seven seats from red to blue in the Iowa State House.

Wednesday November 14, 2018

Blueprint is proud to help flip one seat from red to blue in the Iowa State Senate. https://t.co/R2Y8jXtcFw

Wednesday November 14, 2018

Blueprint is proud to help win five seats in the North Carolina State Senate, breaking the Republican supermajority. https://t.co/1slwChTSQz

Wednesday November 14, 2018

Visit BlueprintTweets ›

Contact Us

202.681.0215

info@blueprintinteractive.com

1155 Connecticut Avenue, NW
Suite 601
Washington, DC 20036

Or submit your info and let us know what we can do for you!