Skip to main content
Skip to main content

API Key Tokens

In this document, you’ll learn how the API Key module generates, revokes, and verifies tokens.

API Key Types

There are two types of API keys:

  • publishable: A public key used in client applications, such as a storefront.
  • secret: A secret key used for authentication and verification purposes, such as an admin user’s authentication token or a password reset token.

The API key’s type is stored in the type attribute of the ApiKey data model.


Publishable Token Generation

When you create a publishable API key, its token is generated using the randomBytes method of Node.js’s crypto package. The token is 32 characters long and is hex-encoded. It’s stored in the token attribute of the ApiKey data model.


Secret Token Generation

When you create a secret API key, three tokens are generated:

  • A token that’s 32 characters long and hex-encoded. It’s generated using the randomBytes method of Node.js’s crypto package.
  • A salt token that’s 15 characters long and hex-encoded. It’s also generated using the randomBytes method.
  • A hashed token is generated from the token and salt token using the scrypt method of Node.js’s crypto package. It’s 64 characters long and hex-encoded.

The salt and hashed tokens are stored in the ApiKey data model’s salt and token attributes, respectively.


API Key Expiration

An API key expires when it’s revoked using the revoke method of the module’s main service. The method sets the API key’s revoked_at and revoked_by attributes accordingly.

The associated token is no longer usable or verifiable.


Token Verification

To verify a token received as an input or in a request, the authenticate method of the module’s main service goes through all non-expired API keys. It recalculates the hash token using the supplied token and the API key’s salt attribute.

If the calculated hashed token matches the one in the database, the token is considered verified.

Was this section helpful?