Authentication overview
Contentful API authentication provides mechanisms to control programmatic access to your content spaces. The choice of authentication method depends on the type of interaction an application or user intends to perform. For read-only access to published content, the Content Delivery API (CDA) and Content Preview API (CPA) utilize API keys. For content creation, modification, or deletion, the Content Management API (CMA) also uses API keys, which carry broader permissions. Integrations requiring user consent or interaction with third-party services often leverage OAuth 2.0 for delegated authorization.
Each API key is scoped to a specific Contentful space and environment, providing granular control over what content can be accessed or modified. This approach enables developers to implement the principle of least privilege, ensuring that applications only possess the necessary permissions for their intended functions. Contentful's authentication framework is designed to support various application architectures, from client-side content rendering to server-side content management systems and automated workflows. Understanding the distinctions between API key types and OAuth 2.0 is critical for designing secure and efficient content-driven applications.
Supported authentication methods
Contentful API supports two primary authentication methods: API keys and OAuth 2.0. Each method is suited for different use cases and security requirements.
API Keys
API keys are unique alphanumeric strings used to authenticate requests to Contentful's APIs. They are the most common method for programmatic access and are categorized by the API they grant access to:
- Content Delivery API (CDA) Keys: These keys provide read-only access to published content. They are suitable for client-side applications, websites, and mobile apps that display public content. CDA keys are generally considered less sensitive than CMA keys because they cannot modify content.
- Content Preview API (CPA) Keys: Similar to CDA keys, CPA keys provide read-only access but include unpublished or draft content. These are primarily used in staging environments or content preview interfaces before publication.
- Content Management API (CMA) Keys: These keys grant read and write access to content, enabling applications to create, update, delete, and publish entries, assets, and content types. CMA keys are highly sensitive and should be treated with the same care as administrative credentials. They are typically used in server-side applications, build processes, and secure backend services.
OAuth 2.0
OAuth 2.0 is an authorization framework that allows third-party applications to obtain limited access to a user's Contentful account without exposing their credentials. This method is ideal for integrations that require user consent or need to perform actions on behalf of a user. Contentful supports the Authorization Code Grant flow for web applications and may support other flows like Client Credentials for specific server-to-server integrations.
- Authorization Code Grant: This flow is used when a user authorizes a third-party application to access their Contentful account. The application redirects the user to Contentful for authorization, receives an authorization code, and then exchanges it for an access token. This token can then be used to make API requests on the user's behalf.
The following table summarizes the Contentful API authentication methods:
| Method | When to Use | Security Level |
|---|---|---|
| Content Delivery API Key (CDA) | Read-only access to published content for public-facing applications (websites, mobile apps). | Low (read-only, public content) |
| Content Preview API Key (CPA) | Read-only access to published and draft content for preview environments. | Medium (read-only, includes drafts) |
| Content Management API Key (CMA) | Read and write access for content creation, updates, and deletion (backend services, build tools). | High (read/write, administrative) |
| OAuth 2.0 (Authorization Code Grant) | Third-party integrations requiring user consent to access Contentful resources on their behalf. | High (delegated access, user-scoped) |
Getting your credentials
To obtain API keys for Contentful, you will typically use the Contentful web application. For OAuth 2.0, you will need to register your application to receive client credentials.
For API Keys
- Log in to Contentful: Access your Contentful account through the Contentful web app.
- Navigate to API Keys: In your space, go to
Settings>API keys. - Create a New Key: Click
Add API key. - Configure Key Details:
- Provide a descriptive name for your key.
- Select the environment(s) the key should apply to.
- For Content Delivery/Preview API keys, choose the desired content preview settings.
- For Content Management API keys, ensure you understand the permissions granted.
- Save and Retrieve: Save the key. Contentful will display the generated API key (access token) and space ID. Copy these values immediately as the access token may not be viewable again for security reasons.
For OAuth 2.0
- Register Your Application: In your Contentful account, navigate to
Organization Settings>OAuth Apps. - Create a New OAuth App: Click
Add new app. - Provide Application Details:
- Enter a name and description for your application.
- Specify the
Redirect URI(s). These are the URLs where Contentful will send the user back after authorization, along with the authorization code. - Define the required
Scopes, which determine the types of permissions your application will request from the user (e.g.,content_management_read,content_management_write).
- Retrieve Client Credentials: After saving, Contentful will provide you with a
Client IDandClient Secret. These are your application's credentials for initiating the OAuth flow.
Authenticated request example
This example demonstrates how to make an authenticated request to the Contentful Content Delivery API using a CDA key. For Content Management API requests, the process is similar, but you would use a CMA key and the CMA endpoint.
Using a Content Delivery API Key (CDA) with cURL
To fetch entries from your Contentful space, you typically include the Authorization header with your API key (referred to as an access token) and specify your Space ID. The example below retrieves entries from a hypothetical space:
curl -X GET \
'https://cdn.contentful.com/spaces/{YOUR_SPACE_ID}/environments/{YOUR_ENVIRONMENT_ID}/entries' \
-H 'Authorization: Bearer {YOUR_CDA_ACCESS_TOKEN}' \
-H 'Content-Type: application/json'
Replace {YOUR_SPACE_ID}, {YOUR_ENVIRONMENT_ID}, and {YOUR_CDA_ACCESS_TOKEN} with your actual credentials. The environments segment is typically master unless you have configured custom environments.
Using a Content Management API Key (CMA) with Python SDK
Contentful provides SDKs for various programming languages, simplifying authentication and API interactions. Here's an example using the Python SDK to create a new entry:
from contentful_management import Client
# Replace with your CMA Access Token
cma_access_token = "YOUR_CMA_ACCESS_TOKEN"
# Replace with your Space ID
space_id = "YOUR_SPACE_ID"
# Replace with your Environment ID (e.g., 'master')
environment_id = "YOUR_ENVIRONMENT_ID"
client = Client(cma_access_token)
# Get the space and environment
space = client.spaces(space_id).find()
environment = space.environments(environment_id).find()
# Get a content type (e.g., 'blogPost')
content_type = environment.content_types().find('blogPost')
# Create a new entry
entry_data = {
'fields': {
'title': {'en-US': 'My New Blog Post'},
'slug': {'en-US': 'my-new-blog-post'},
'body': {'en-US': 'This is the content of my new blog post.'}
}
}
new_entry = environment.entries().create(content_type.id, entry_data)
print(f"Created entry with ID: {new_entry.id}")
print(f"Entry title: {new_entry.title}")
This Python example demonstrates how to initialize the Contentful Management client with a CMA access token and then use it to interact with content types and entries. The SDK handles the underlying HTTP requests and authentication headers.
Security best practices
Securing your Contentful API credentials is paramount to maintaining the integrity and confidentiality of your content. Adhering to best practices helps prevent unauthorized access and potential data breaches.
- Never Expose CMA Keys in Client-Side Code: Content Management API (CMA) keys grant read and write access. Embedding them directly in client-side JavaScript, mobile apps, or any publicly accessible code makes your content vulnerable to unauthorized modification or deletion. Always use CMA keys in secure backend environments.
- Use Environment Variables for Credentials: Store all API keys and OAuth client secrets as environment variables, especially in production environments. This prevents hardcoding credentials directly into your codebase, making them easier to manage, rotate, and secure. Many CI/CD pipelines and hosting providers offer secure ways to manage environment variables.
- Implement the Principle of Least Privilege: Grant only the necessary permissions to each API key or OAuth application. For example, if an application only needs to display published content, use a Content Delivery API (CDA) key instead of a Content Management API (CMA) key. Regularly review and revoke unnecessary permissions.
- Rotate API Keys Regularly: Periodically generate new API keys and update them in your applications. This practice limits the window of opportunity for an attacker if a key is compromised. The frequency of rotation depends on your organization's security policies and risk assessment.
- Restrict API Key Access by IP Address (if available): If your infrastructure supports static IP addresses, configure Contentful (if the feature is available for your plan) to only accept requests from a whitelist of trusted IP addresses. This adds an extra layer of security, preventing unauthorized requests originating from unknown locations.
- Secure OAuth Redirect URIs: When configuring OAuth applications, ensure that your redirect URIs are specific and secure (e.g., using HTTPS). Avoid wildcard redirect URIs unless absolutely necessary and thoroughly justified, as they can be exploited in redirection attacks.
- Monitor API Usage: Keep an eye on your Contentful space's activity logs for any unusual or suspicious API requests. Anomalies could indicate a compromised key or unauthorized access attempts.
- Utilize Contentful's Webhooks for Event-Driven Security: Configure webhooks to be notified of significant events (e.g., content changes, asset uploads). While not directly an authentication mechanism, webhooks can be part of a broader security strategy to detect and respond to unauthorized actions.
- Educate Your Team: Ensure all developers and team members understand the importance of API key security and follow established best practices.