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.
import type { CollectionConfig } from 'payload'
export const ThirdPartyAccess: CollectionConfig = {
slug: 'third-party-access',
auth: {
useAPIKey: true,
},
fields: [],
}
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.
import Users from '../collections/Users'
const response = await fetch('http://localhost:3000/api/pages', {
headers: {
Authorization: `${Users.slug} API-Key ${YOUR_API_KEY}`,
},
})
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.
import type { CollectionConfig } from 'payload'
export const ThirdPartyAccess: CollectionConfig = {
slug: 'third-party-access',
auth: {
useAPIKey: true,
disableLocalStrategy: true,
},
}