The difficulty of naming lies in making the definitions of variables, constants, functions, or classes clear and concise, without ambiguity. If we cannot understand a variable clearly, then its name is not accurate enough.
API keys and tokens have this problem, as they both serve as an authentication mechanism. A few days ago, during a discussion, someone mentioned that these two terms can be used interchangeably. About two minutes later, I had to stop the conversation and say, "You should know that they are different, right?" After saying this, there was silence in the room, apparently they did not know. It turns out that many people cannot tell me the difference between an API key and a token. Therefore, in this text, I will introduce the difference between them to everyone.
Definitions#
We can distinguish API keys and tokens through the following definitions.
- API key - A value provided when calling an API through code, used to identify and authorize the caller. It is intended to be used programmatically and is usually a long string of letters and numbers.
- Token - A piece of data representing a user session or specific permissions. It is used by individual users for a limited period of time.
Generation Methods#
The methods for creating API keys and tokens are usually different.
- API key - Usually created once through a user interface and can be used continuously until rotation, or it can be configured to expire after a certain period of time.
- Token - Dynamically generated upon successful verification or login. It usually has a short expiration time but can be refreshed for a longer period.
Scope of Permissions#
The scope of permissions refers to what functions can be performed when using the provided authentication methods.
- API key - Fixed set of application-level permissions. Whoever possesses the API key can access the allowed resources.
- Token - Limited to specific data or functions that individual users have access to. This may be influenced by roles or other business-level requirements. It often focuses more on data restrictions.
Security#
How secure are they? If an API key or token is leaked or obtained by malicious users, how severe is the potential damage?
- API key - Due to the fact that these keys are usually long-term and provide unrestricted access to data, if leaked, they can cause catastrophic consequences. Revoking the API key is usually the only solution to the problem. Applications typically need to have good observability to identify compromised keys and find malicious users.
- Token - Security has been taken into consideration during design. Tokens are usually short-lived and easily revocable. A compromised token only has access to the data scope that the user is authorized to access and will expire automatically.
Usage#
When would you use one instead of the other? It seems that they have struck a good balance between advantages and disadvantages.
- API key - Used for server-to-server communication, such as accessing public data like weather APIs or integrating with third-party systems.
- Token - Used for user authentication, fine-grained access control (FGAC), granting temporary access to resources, browser access permissions, and managing user sessions.
Examples#
Now that we understand the difference between the two, let's take a look at two practical examples using the Momento JavaScript SDK.
API key
As mentioned earlier, API keys are usually created in a user interface. Considering privacy, I don't have an actual API key to share. However, here is how you, as a user, can obtain an API key through the Momento console.
You can select the desired permissions, set an optional expiration date, and click "Generate API Key". Then, you can use this API key in your workflow.
Token
Contrast this with a user-based one-time token generated upon successful login. Let's take an example based on roles, where a user has read-only access to calendar event caching but has access to publish and subscribe to collaboration topics.
// called on successful login
exports.handler = async (event) => {
const user = await loadUserMetadata(event.userId);
let token;
switch(user.role){
case 'data-entry':
token = await getDataEntryToken(user.tenantId);
break;
case 'admin':
token = await getAdminToken(user.tenantId);
break;
default:
throw new Error('Role not supported');
}
return token;
};
const getDataEntryToken = async (tenantId) => {
const scope = {
permissions: [
{
role: 'readonly',
cache: 'calendar-events',
item: {
keyPrefix: tenantId
}
},
{
role: 'publishsubscribe',
cache: 'collaboration',
topic: `${tenantId}-events`
}
]
};
const response = await authClient.generateDisposableToken(scope, ExpiresIn.minutes(15));
return {
token: response.authToken,
expiresAt: response.expiresAt.epoch()
};
};
As seen here, we create a token with a validity of 15 minutes, with read-only access to calendar functionality and only allowing access to cache items starting with the user's tenantId. Therefore, we limit the functionality and data based on the user's attributes.
Summary
API keys and tokens each have their own advantages and disadvantages. One is not necessarily better than the other. When deciding which authentication mechanism to apply, consider your application scenario. Use tokens for user session authentication scenarios and API keys for providing authentication to third-party systems.