API Keys are one of the more popular ways to secure the access to a REST API. They are an easy method to grant and manage access to an API and track its usage. According to Blobr’s own API Portal report, 67% of the top 100 API companies use API Keys, while the other 33% prefer OAuth. However, API Keys require basic attention to avoid basic security threats. Here’s a checklist of the best practices to secure your API key.
Never use HTTP. HTTPS is your friend.
How to use API keys?
Do not use API keys in URLs, they could be captured and exploited. HTTPS encrypts URLs but they may appear in clear at some point in the web server logs.
The preferred option is to put them in the HTTPS header, or in the body for a POST.
Prefer this method:
How to hide API keys?
In the example above, the API key is clearly displayed in the code, which is not a good practice.
The key should be retrieved from a database, a Secret Manager, or from your environment for instance.
Avoid one-key-does-everything systems. If your API has only one security mechanism that allows full access to all the endpoints without restrictions, you’d better trust the people you are giving this sesame away.
Scopes should be used to limit the rights on objects or records that are manipulated and on operations allowed (read/write/update/delete).
The principle of Least Privilege (PoLP) should apply.
Rotate API keys
API keys shouldn’t last forever and your implementation should allow to regenerate them periodically.
When rotating a key, both the provider and consumers need to be updated simultaneously. If you first generate a new key on the API side, subsequent calls made by API consumers may end up with errors (unauthorized access) until the key is also updated on their side.
A good practice is to systematically create two keys for any API, a primary and a secondary.
On the consumer side, the caller may try first with the primary key and in case of error, fallback to the secondary one:
By implementing this pattern, it is possible to rotate the two keys in two steps without getting any errors.
Begin by rotating the first key and update the database/secret/environment where the key is stored on the client side, then repeat the operation with the secondary key.
Those simple steps will greatly reduce the chance of security incidents, for both the provider and the consumer.