Securing Your API With Long-Lived Authentication Keys (With A Deep-Dive!)
Tags: webdev, security, api, dotnet
Published: 2022-02-24 19:34:29

---
title: Securing Your API With Long-Lived Authentication Keys (With A Deep-Dive!)
published: true
description: Why and how would you secure your API with long-lived authentication keys? This is a look at why and how ProcedureFlow used long-lived API keys for their API.
tags: webdev, security, api, dotnet
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7az2okah0n3rxmldpbq.jpeg
canonical_url: https://medium.com/procedureflow-engineering/building-api-authentication-at-procedureflow-4d1fe78bb293
---

There comes a time in the life of a multi-tenant SAAS company when its larger customers need the automation and power of an API. The multitude of reasons includes scaling user provisioning, integrating with other products, facilitating advanced reporting and more.

If you're in this position, one of the most important areas you need to think about carefully is authentication. There are many different factors to consider:

- Is your API responding to server-to-server requests? Or will you need to support other types of clients like web applications, mobile, etc.?
- Do you need long-lived or short-lived tokens?
- What about OAuth? Does that make sense right now?
- Should you jump on the JWT bandwagon?
- How will your customers configure authentication? How does your choice on this affect their user and developer experience?

At ProcedureFlow, we've spent a fair amount of time researching how the best APIs out there have implemented API authentication: [Stripe](https://stripe.com/), [Slack](https://slack.com/), [GitHub](https://github.com/), [Twilio](https://www.twilio.com/) and others. We want to make sure our API is really easy to use, gives superpowers to our customers and is rock-solid secure.

![Rock solid API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/satsyxv91za4mo6y9pwe.png)

Needless to say, this one area can get overwhelming quickly! To figure out what works best for your company's needs, you have to start by thinking about the requirements of your API.

## Minimum Viable API
If you're a startup like us, then you won't have the time and resources to build a complete API that will integrate with "all the things" immediately. You have to identify what API products make sense as a priority. Then, you can build your foundational API infrastructure, that first API product and iterate based on your customer's feedback.

![Use An Iterative Approach To API Product Development](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/euz4xqey29e47kfcawrj.png)

For example, we decided to build a [SCIM API](http://www.simplecloud.info/) first.

Authentication is one of the areas where SCIM is flexible - so we can use the mechanism that works best for our custom API and use it for SCIM too 👍.

Based on our requirements, there were a few smaller decisions we had to make first:

- We'd be focusing on server-to-server APIs for the first few API products so this influences what kind of authentication mechanism makes sense for us.
- We wanted to retain the ability to implement other authentication mechanisms in the future.
- [TTFC (Time-to-first-call)](https://blog.postman.com/the-most-important-api-metric-is-time-to-first-call/) is considered one of the most important API metrics. Configuring authentication should be as simple as possible for our customers to facilitate a low TTFC.
- How do well-designed APIs like Stripe, Twilio, Slack, Twitter and GitHub do things? What can we learn or implement ourselves?

## The Big Decision
Your overall decision will be based on a balance between valuing ease of use for your customers and enforcing solid security.

![ease-of-use vs. security](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0s0s0dg2zlnb3mt1k68l.png)

At ProcedureFlow, we decided to use a long-lived API key that our customers can generate from within our product. This is similar to how [Stripe](https://stripe.com/docs/keys) and [Twitter V2](https://developer.twitter.com/en/docs/tutorials/step-by-step-guide-to-making-your-first-request-to-the-twitter-api-v2) do API authentication. We generate both a `client_id` and a `client_secret` (more on these later 😉).

Some of the qualities and behaviors of using a long-lived API key includes:

- API keys can be tied to individual tenants or specific users [like Slack does](https://api.slack.com/authentication/token-types).
- Can be scoped to specific products or features [like Stripe](https://stripe.com/docs/keys#limit-access) does, with read-only or read/write access per feature.
- Also inspired by [Stripe's approach](https://stripe.com/docs/keys#rolling-keys), customers can have a user-friendly UI to generate new keys, revoke them immediately or revoke them with a grace period.
- API secrets should be hidden on the UI, except when first generated. This is mainly inspired by [Stripe's approach](https://stripe.com/docs/keys#safe-keys) and is a best practice. You don't want those secrets getting leaked!

Another thing we chose to do is prefix our key values. This makes them easier to identify and makes the type of key/token more explicit. This technique is inspired by Stripe and GitHub - [who have recently switched to this format too](https://github.blog/2021-04-05-behind-githubs-new-authentication-token-formats/).

## Deep-Dive: Long-lived API Token Authentication
Let's deep-dive into some of the more detailed decisions we had to make and why they might make sense for you too.

### The Anatomy Of An API Key
Services like Stripe, Slack and Twilio use two values for their long-lived API keys. Slack, for example, calls these [the Client Id and Client Secret](https://api.slack.com/authentication/best-practices#slack_apps__client-id-and-secret). Stripe calls them [the Publishable and Secret Keys](https://stripe.com/docs/keys#obtain-api-keys). Other vendors have used other terms like "Access Key" and "Access Key Secret".

We have chosen to call ours `client_id` and `client_secret`. This helps to set us up for future use-cases around delegated authorization (e.g. OAuth) and is consistent with the standard OAuth naming terminology. Also, each token can be used by a specific client - web, mobile, server, etc. so `client_id` seems more semantically accurate to us than other options like `app_id`, `access_key` or `public_key`.

### Public Identifier
The `client_id` is used to identify the user or owner of the API key.

This is helpful when you may have multiple types of clients that use your API keys - web applications, mobile applications, back-end systems, etc. It also helps when tokens can be assigned to specific users in your system. You can use the `client_id` to peg rate limits per client, logging metrics that are tied to the identifier, etc.

### Secret Token
The `client_secret` is a random cryptographically generated token.

When thinking about the technical aspects of implementing API key authentication, one of the most important issues to make sure you consider is that _API secrets are [just like passwords](https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/)._

It is inappropriate to store these tokens as plain-text for the same reasons you wouldn't store passwords as plain-text. Even worse, API secrets are present for every HTTP request, so you want to make sure to protect them well.

Like passwords, API secrets ought to be hashed when stored in a database or some other tool like a cache. If an attacker ever managed to get access to your database, then they could start impersonating your customers by using plain-text API secrets.

![identity vs. authorization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5z0oyqpgux4s2pu91lx9.png)

### Other Security Considerations
One of the reasons you may not want to only use a "secret" value, even if hashed, is that it becomes both the secret and the lookup value.

When an API request comes into your system, and if all you have is the secret value, then you would have to hash the secret and check if it exists in your database. If it does exist, then you know who owns the API key and therefore who's allowed to perform the API request.

Your SQL query would look similar to the following:

```
select * from api_auth_keys where secret_hash = $secret_hash
```

One potential problem with this approach is that it [could be susceptible to timing attacks](https://blog.ircmaxell.com/2014/11/its-all-about-time.html). While in practice there are multiple ways to mitigate these kinds of security vulnerabilities, the issue simply disappears if you use a different value as the identifier for the lookup - assuming you compare the hashes in memory by using a safe constant time comparison function.

### Bearer Token
At the moment, we are only using API keys for server-to-server communication. This means our customer's servers will need to communicate directly with our API as opposed to via some delegated third-party system (which would require something like OAuth).

Because of this, we can combine both the `client_id` and `client_secret` and display that to our users as one value. This helps with ease of use and user experience, yet allows us to still gain the benefits of using a [split token approach](https://paragonie.com/blog/2017/02/split-tokens-token-based-authentication-protocols-without-side-channels).

![Bearer Token Using A Split Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acttyqv0nzqvgj6njt06.png)

### Best Hashing Algorithm?
PBKDF2 is one of the most popular and reliable hashing algorithms today. It's a great algorithm for password hashing because it's slow and cryptographically sound. You don't want attackers to brute-force guess passwords quickly, so PBKFD2 makes that process much slower and therefore harder to attack.

That's great - but one of the hallmarks of any high-quality API is having a short response time. This affects developer experience, can cause more load on servers (which means paying money for more servers), can affect contractual issues due to not meeting certain SLAs and can affect the overall perception of your products and company.

_Is PBKFD2 the best option then?_

SHA256 is another common hashing algorithm that is solid - but it's quick to compute hashes. But, is there a way to use SHA256 so that hashes are still computed quickly but have high entropy so that attackers can't brute force API tokens within a reasonable amount of time?

Two core problems with user-supplied passwords are that they are generally _short and predictable_. So, what you need are API tokens that are long and random!

![SHA256 Hash](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6wg9eq7kt6t4bz7tiibb.png)

This is what we did - we opted to generate very long random values for our `client_secret` - and we hash this using SHA256.
The code for this might look like the following:

{% embed https://gist.github.com/jamesmh/afe87e61011ed28348dac832a36280ef %}

### Storing API Tokens
You already know that you should store the hash of an API secret. However, you might also want to store the last few digits of your API secret.

[Like Stripe](https://stripe.com/docs/keys#safe-keys), you should only show the raw API secret immediately after it is created. From that point forward, show the last few digits of the token on the UI. This helps customers identify which key they want to revoke, change scopes for, etc.

We opted to follow suit with Stripe and keep 4 digits from our non-hashed API secrets.

![Mock API Key Schema](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zkv5r735s5c98ydr2i0a.png)

The `client_id` column would also benefit from using an index so that your database lookups performed during incoming API request authentication are fast 🚀.

### API Token Pipeline
Whatever technology stack you are using, you'll want to verify any incoming API tokens early in the lifetime of an HTTP request.

While .NET can sometimes get a bad rap, we use it for reasons like being one of the [most secure web development platforms out there](https://octoverse.github.com/static/github-octoverse-2020-security-report.pdf), having most of the basic tools you'll need for web development out of the box and having a robust type system. We might write more on that topic another time 😅.

.NET's MVC framework has a flexible middleware system that's easy to hook into. We use the built-in middleware (a.k.a. "filters") to process API tokens early in the HTTP pipeline.

Here's the flow of how we process bearer tokens when authenticating against our API:

1. A client issues an HTTP request with an API token as a bearer token.
1. We intercept the bearer token early in the HTTP pipeline.
1. We split the token into `client_id` and `client_secret`.
1. Using `client_id` we check if a row exists in the database.
1. We hash the user input `client_secret` and use a constant-time comparison function to verify that it matches the stored hash.
1. We create a "session" object that only exists in memory for the lifetime of the HTTP request.
1. Other events occur downstream that use the API key - like rate limiting.

![API authentication process](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ormis7po5bqwj5u2l37v.png)

The core of our API authentication middleware looks roughly like the following:

{% embed https://gist.github.com/jamesmh/09034cb17324000f81bc8beb8281e911 %}

## Conclusion
There's much more you'll have to consider when implementing API authentication and API tokens in particular:

- Resource/feature scopes
- UI elements
- Logging
- Tracking token usage for troubleshooting
- Database indexing
- Rate limiting
- Etc.

For example, we had to extend our existing Redis-based rate-limiting to support limiting based on API keys. Originally, limit data was not being made available to the caller. We had to modify our LUA scripts to return rate limit data and then assign values to the appropriate HTTP headers.

We do our best at working fast and smart so that we can deliver value to our customers quickly. But we also care about the details, especially when decisions we make now can have an impact on the future of our products. For example, choosing to prefix our API tokens may seem insignificant at face value, but it affects user experience, the overall security of our API, and is not trivial to change in the future.

If you like solving problems like the ones we've discussed and you're interested in the possibility of joining our team then check out our [open positions](https://procedureflow.com/jobs)!