API Key Strategy
To integrate with third-party APIs or services, you might need the ability to generate API keys that can be used to identify as a certain user within Payload. API keys are generated on a user-by-user basis, similar to email and passwords, and are meant to represent a single user.
For example, if you have a third-party service or external app that needs to be able to perform protected actions against Payload, first you need to create a user within Payload, i.e. dev@thirdparty.com
. From your external application you will need to authenticate with that user, you have two options:
- Log in each time with that user and receive an expiring token to request with.
- Generate a non-expiring API key for that user to request with.
Technically, both of these options will work for third-party integrations but the second option with API key is simpler, because it reduces the amount of work that your integrations need to do to be authenticated properly.
To enable API keys on a collection, set the useAPIKey
auth option to true
. From there, a new interface will appear in the Admin Panel for each document within the collection that allows you to generate an API key for each user in the Collection.
User API keys are encrypted within the database, meaning that if your database is compromised, your API keys will not be.
HTTP Authentication
To authenticate REST or GraphQL API requests using an API key, set the Authorization
header. The header is case-sensitive and needs the slug of the auth.useAPIKey
enabled collection, then " API-Key ", followed by the apiKey
that has been assigned. Payload's built-in middleware will then assign the user document to req.user
and handle requests with the proper Access Control. By doing this, Payload recognizes the request being made as a request by the user associated with that API key.
For example, using Fetch:
Payload ensures that the same, uniform Access Control is used across all authentication strategies. This enables you to utilize your existing Access Control configurations with both API keys and the standard email/password authentication. This consistency can aid in maintaining granular control over your API keys.
API Key Only Auth
If you want to use API keys as the only authentication method for a collection, you can disable the default local strategy by setting disableLocalStrategy
to true
on the collection's auth
property. This will disable the ability to authenticate with email and password, and will only allow for authentication via API key.