Implementing API keys for my API

LuckyLuke picture LuckyLuke · Jan 4, 2013 · Viewed 8.3k times · Source

I have created an api and I want to have some control over who uses it, how often etc. I want to have an API key strategy so that the users must provide the key in order to use the API. However i don't know how to implement it. The users are registered with username and password. What i thought of was to assign a UUID when the user logs in and store it in a table in the database. Then each request includes this uuid and it is checked on each request at the server.

However this does not seem right. Could someone explain the steps in order to create an api key like, dropbox, twitter, facebook etc. does? I want to try to implement this myself.

Answer

Kristian picture Kristian · Jan 4, 2013

Could someone explain the steps in order to create a api key like, dropbox, twitter, facebook etc. does? I want to try implement this myself.

Generating The API Key

  1. choose some encryption / decryption method you'd like to use
  2. choose a salt that you will add to the data before encryption
  3. decide what data you want inside the encrypted string: timestamp, Uid, roles, etc. The timestamp is the most useful part of this, because using the timestamp, you can restrict requests that come from a key older than some time, thus requiring a new key to be generated.
  4. bundle it in something you can parse later once decrypted. Some people use json objects, some do char-delimited strings

Note: if you don't want it to be a decryptable key, as in, it is hashed and thus infinitely more difficult to crack, then you can simply follow this stratgey: make a set of steps to form your unhashed data string: sha1("some-secret"."some-other-bit-of-info"."etc"."etc") and then the API consumer has the onus on them to generate their own key. Thus, they have access only if they have the necessary parts / info needed to construct it.

Consuming the API

Take Stripe's API as a decent example:

  1. make authorization request: an API key is returned. "curl uses the -u flag to pass basic auth credentials (adding a colon after your API key will prevent it from asking you for a password)." --Stripe Docs

  2. send that key along with all further requests.