Authentication overview
Contentful provides authentication mechanisms to secure access to its Content Delivery API (CDA), Content Preview API (CPA), and Content Management API (CMA). The choice of authentication method depends on the type of access required and the operational context, ranging from public content retrieval to administrative content manipulation. Contentful's authentication framework is designed to integrate with various application architectures and development workflows, ensuring that only authorized entities can interact with content spaces and their associated data.
For read-only access to published content, API keys are the standard and most straightforward method. These keys grant immediate access to specific content spaces without user interaction, making them suitable for public-facing applications or static site generators. Contentful distinguishes between Content Delivery API keys for published content and Content Preview API keys for draft content, allowing developers to test changes before deployment.
When write access, user-specific permissions, or third-party application integration is necessary, Contentful employs OAuth 2.0. This protocol enables applications to obtain delegated authorization from users to access their Contentful resources without sharing user credentials directly. OAuth 2.0 is critical for scenarios involving content creation, updates, deletions, or when an application needs to act on behalf of a Contentful user. Contentful's implementation of OAuth 2.0 supports common grant types, facilitating secure and granular access control for complex integrations and administrative tasks.
All API requests to Contentful must include valid authentication credentials to receive a successful response. Failure to provide correct authentication results in a 401 Unauthorized or 403 Forbidden HTTP status code, indicating that the request lacks valid authentication credentials or the provided credentials do not grant access to the requested resource.
Supported authentication methods
Contentful supports two primary authentication methods: API keys and OAuth 2.0. Each method is designed for specific use cases and offers different levels of security and control.
API Keys
API keys are long, randomly generated strings that grant access to your Contentful content. They are primarily used for programmatic access to the Content Delivery API (CDA) and Content Preview API (CPA). These keys are associated with a specific content space and environment, providing read-only access to content.
- Content Delivery API (CDA) Keys: Used for retrieving published content. These keys are suitable for client-side applications, static site generators, and any scenario where public read-only access to content is acceptable.
- Content Preview API (CPA) Keys: Used for retrieving both published and draft content. These keys are valuable during development and content review processes, allowing developers and content editors to see changes before they go live.
- Content Management API (CMA) Tokens: While technically a type of API key, CMA tokens are distinct as they provide read and write access to a content space. They are used for administrative tasks such as creating, updating, and deleting content, managing content types, and configuring webhooks. CMA tokens should be treated with the highest level of security due to their elevated permissions.
OAuth 2.0
OAuth 2.0 is an authorization framework that enables applications to obtain limited access to a user's Contentful account on behalf of the user. It is typically used for third-party applications, integrations requiring user-specific permissions, or when an application needs to perform actions that modify content or settings within Contentful.
- Authorization Code Grant Type: This is the most common and secure OAuth 2.0 flow for web applications. It involves redirecting the user to Contentful for authorization, after which Contentful redirects them back to the application with an authorization code. The application then exchanges this code for an access token and a refresh token. This flow ensures that the user's credentials are never exposed to the client application. For more details on this grant type, refer to the OAuth 2.0 Authorization Code Grant documentation.
- Client Credentials Grant Type: This flow is used when an application needs to access its own service account or act on its own behalf, rather than on behalf of a user. It's suitable for server-to-server interactions where there is no user context. The application authenticates directly with Contentful using its client ID and client secret to obtain an access token.
The following table summarizes Contentful's authentication methods:
| Method | When to Use | Security Level |
|---|---|---|
| Content Delivery API Key (CDA) | Read-only access to published content (e.g., public websites, mobile apps) | Moderate (read-only, minimal risk if exposed) |
| Content Preview API Key (CPA) | Read-only access to draft and published content (e.g., development, content review) | Moderate (read-only, minimal risk if exposed) |
| Content Management API Token (CMA) | Read/write access to content and content types (e.g., administrative tools, backend services) | High (full control over content space, high risk if exposed) |
| OAuth 2.0 (Authorization Code) | Third-party applications requiring user-delegated access (e.g., integrations, user-facing apps) | High (token-based, user-scoped permissions, refresh tokens) |
| OAuth 2.0 (Client Credentials) | Server-to-server communication, applications acting on their own behalf (e.g., automated scripts) | High (application-scoped permissions, direct authentication) |
Getting your credentials
Obtaining the necessary authentication credentials for Contentful involves different steps depending on whether you need API keys or OAuth 2.0 credentials.
API Keys (CDA, CPA)
- Log in to Contentful: Access your Contentful web app at app.contentful.com.
- Navigate to API Keys: From the main dashboard, select your desired space. In the left sidebar, go to Settings and then API keys.
- Add API Key: Click the "Add API key" button.
- Configure Key: Provide a name for your API key. Contentful automatically generates a Content Delivery API key and a Content Preview API key for the selected space and environment.
- Copy Keys: Copy and securely store the generated "Space ID", "Content Delivery API - access token", and "Content Preview API - access token". These values are displayed on the API key details page.
Content Management API (CMA) Tokens
CMA tokens are personal access tokens that grant read/write access and are tied to a user account. They should be handled with extreme care.
- Log in to Contentful: Access your Contentful web app.
- Navigate to Content Management API: In the left sidebar, go to Settings and then Content Management API.
- Generate Personal Access Token: Click "Generate personal token".
- Configure Token: Give the token a descriptive name and select the space and environment it should have access to. You can also specify the token's scope (read-only or full access).
- Copy Token: Copy the generated token immediately. It will only be shown once.
OAuth 2.0 Credentials
For OAuth 2.0, you need to register your application with Contentful to obtain a client ID and client secret.
- Log in to Contentful: Access your Contentful web app.
- Navigate to OAuth Apps: In the left sidebar, go to Settings and then OAuth Apps.
- Register New App: Click "Register new app".
- Provide App Details: Fill in your application's name, description, and importantly, the "Redirect URLs" (or "Callback URLs"). These are the URLs where Contentful will redirect the user after they authorize your application. For secure OAuth 2.0 implementation, these URLs must be HTTPS.
- Generate Credentials: After registering, Contentful will provide you with a "Client ID" and "Client Secret". Securely store these credentials. The client secret should never be exposed in client-side code.
Authenticated request example
This example demonstrates how to make an authenticated request to the Contentful Content Delivery API (CDA) using a Content Delivery API key. The example uses curl for simplicity, but the same principle applies to any HTTP client or Contentful SDK.
First, ensure you have your Contentful Space ID and Content Delivery API access token. You can find instructions for obtaining these in the Contentful authentication documentation.
Example: Fetching an entry by ID using curl
curl -X GET \
'https://cdn.contentful.com/spaces/{SPACE_ID}/environments/{ENVIRONMENT_ID}/entries/{ENTRY_ID}' \
-H 'Authorization: Bearer {CDA_ACCESS_TOKEN}' \
-H 'Content-Type: application/vnd.contentful.delivery.v1+json'
Replace the placeholders:
{SPACE_ID}: Your Contentful Space ID.{ENVIRONMENT_ID}: The ID of your environment (e.g.,master).{ENTRY_ID}: The ID of the specific content entry you want to retrieve.{CDA_ACCESS_TOKEN}: Your Content Delivery API access token.
Example: Using a Contentful SDK (JavaScript)
Contentful provides official SDKs that simplify authentication and API interactions. Here's an example using the JavaScript SDK to fetch entries:
const contentful = require('contentful');
const client = contentful.createClient({
space: '{SPACE_ID}',
environment: '{ENVIRONMENT_ID}', // defaults to 'master'
accessToken: '{CDA_ACCESS_TOKEN}'
});
client.getEntries({
content_type: 'blogPost'
})
.then((response) => {
console.log(response.items);
})
.catch(console.error);
In this JavaScript example:
- The
contentful.createClient()method initializes the client with your Space ID, environment, and Content Delivery API access token. - The
client.getEntries()method then fetches entries of a specific content type without needing to manually add the authorization header. The SDK handles the authentication details internally.
For more detailed SDK examples across different languages, consult the Contentful SDK documentation.
Security best practices
Implementing strong authentication is crucial for protecting your Contentful content. Adhere to these best practices to minimize security risks:
- Never commit API keys or access tokens to version control: API keys, especially CMA tokens and OAuth client secrets, should never be hardcoded or committed to public or private repositories. Use environment variables, secret management services (e.g., AWS Secrets Manager, Google Secret Manager), or a
.envfile for local development. The Google Cloud Secret Manager overview provides guidance on managing secrets securely. - Use environment-specific keys: Create separate API keys for development, staging, and production environments. This limits the blast radius if a key is compromised in a non-production environment.
- Restrict API key scopes: When generating CMA tokens or configuring OAuth apps, grant only the minimum necessary permissions. For example, if an application only needs to read content, do not grant it write access.
- Rotate API keys and tokens regularly: Periodically generate new API keys and tokens and revoke old ones. This reduces the window of opportunity for an attacker if a key is compromised without your knowledge.
- Implement OAuth 2.0 securely:
- Always use HTTPS for redirect URIs and all communication.
- Validate the
stateparameter in OAuth 2.0 authorization flows to prevent Cross-Site Request Forgery (CSRF) attacks. - Store refresh tokens securely and invalidate them if suspicious activity is detected.
- Protect your Contentful account:
- Enable Multi-Factor Authentication (MFA) for all Contentful user accounts.
- Use strong, unique passwords for Contentful user accounts.
- Regularly review user permissions and access to your Contentful spaces.
- Monitor API usage: Keep an eye on your Contentful API usage metrics for unusual spikes or patterns that could indicate unauthorized access or abuse.
- Client-side API key exposure: For Content Delivery API (CDA) keys, which are read-only, it is generally acceptable to expose them in client-side code (e.g., JavaScript in a static site). However, always ensure these keys only have read access to published content and cannot modify your content space. Never expose CMA tokens or OAuth client secrets on the client side.