There are three standard ways to manage API Authentication these days: API keys, OAuth tokens and JSON Web tokens (JWT). Adam Duvander over at the Zapier engineering blog explains how and when to use them.
The humble API Key is the common and earliest form of API authentication. In its favor is its simplicity. You simply copy and paste your unique key into your app and away you go. The big downside is: they’re not so secure. The same key generally does everything (update/add/delete) and is used in many places. You only need a rogue script or user to result in massive data deletions that create havoc. As a best practice, Adam recommends only sending your API key in the HTTP header. And if possible, create multiple keys for each user so that one can be revoked in cases of a security breach. Even with these best practices, Adam suggests using another form of authentication if you can.
OAuth tokens would be a better bet, since they ensure that end-users never have to worry about securing API keys. They can usually just click a button to allow the API access to one of their existing accounts (e.g. Google).
OAuth was known for being tricky in the early days but with OAuth 2.0 all you need to understand are access and refresh tokens. The access token gives you the ability to access someone’s account while the refresh token lets you receive a new access token if the old one expires. Like API keys, tokens can appear in a variety of places (e.g. the Endpoint string) but again Adam recommends putting the token in the HTTP header.
The access token shares the downside of the API key that a rogue user in possession of the token could add and delete data. But unlike API keys access tokens can be limited in scope and they expire, which limits the damage done. Even better, they can be revoked any time.
JWT tokens are best thought of in combination with OAuth. JWTs can store any kind of data. This means you can add details into them that give you the security benefits of OAuth but with fewer db lookups. The reason is that a JWT can contain a base64 encoded version of the data needed to determine the powers and identity of the API client. In this way, you can avoid a db lookup that checks who the access token belongs to. The downside of JWT is that without a db check, you can’t revoke a token. To mitigate this, Adam suggests using JWT with refresh tokens and expiry dates. Then you can check the JWT signature with every call to ensure the expiry date is in the future and still avoid a db request.
Adam concludes by saying that API keys are fine if the API is to be used only by devs for internal apps that don’t require access to more than one user’s data. But OAuth tokens are the way to go if you want to manipulate many users’ data. Finally, combining OAuth with JWT could be a good idea if you really need to avoid database lookups and revoking access tokens is not such a big deal.