Authentication overview

DatoCMS secures access to its APIs using API tokens, which function as bearer tokens for authentication. These tokens are essential for interacting with both the Content Delivery API (CDA) and the Content Management API (CMA). The CDA is designed for retrieving published content, typically for front-end applications, while the CMA allows for programmatic content creation, updates, and deletions. Each API token is associated with specific permissions and scopes, granting granular control over what actions can be performed and which content can be accessed within a DatoCMS project.

When an API request is made to DatoCMS, the provided API token is validated against the project's configured permissions. This mechanism ensures that only authorized entities can perform operations, safeguarding content integrity and preventing unauthorized data access. The use of bearer tokens is a common practice in modern web APIs, offering a straightforward yet effective method for securing API endpoints. For a broader understanding of API security, the IETF RFC 6750 defines bearer token usage in HTTP authentication schemes.

Supported authentication methods

DatoCMS primarily supports API tokens for authenticating requests to its Content Delivery and Content Management APIs. These tokens are passed in the Authorization header of HTTP requests using the Bearer scheme. Different types of API tokens are available, each designed for specific use cases and levels of access.

Method When to Use Security Level
Content Delivery API Token (Read-only) Retrieving published content for public-facing applications (e.g., websites, mobile apps). High (read-only access, limited scope)
Content Management API Token (Read/Write) Programmatically managing content (create, update, delete) from trusted back-end services or CI/CD pipelines. Moderate (requires careful handling due to write access)
Preview API Token (Read-only) Retrieving draft and unpublished content for preview environments. High (read-only access to drafts, limited scope)

The Content Delivery API tokens are typically read-only and are suitable for client-side applications where content retrieval is the primary function. Content Management API tokens, conversely, grant read and write access, making them suitable for server-side operations, integrations, and automated content workflows. Preview API tokens offer the ability to fetch unpublished content, which is useful for staging or development environments before content goes live. Each token type is configured with specific permissions within the DatoCMS project settings, allowing administrators to define precise access controls.

Getting your credentials

To obtain API tokens for DatoCMS, you need to access your project settings within the DatoCMS administrative interface. The process involves navigating to the 'API tokens' section, where you can generate new tokens and manage existing ones. DatoCMS documentation provides a detailed guide on how to create API tokens.

  1. Log in to DatoCMS: Access your DatoCMS project dashboard.
  2. Navigate to Project Settings: Click on 'Settings' in the sidebar, then select 'API tokens'.
  3. Create a New Token: Click the 'New API token' button.
  4. Configure Token Permissions:
    • Name: Provide a descriptive name for the token (e.g., "Website Frontend Read-Only").
    • API Type: Choose between 'Content Delivery API' (for read-only access to published content), 'Content Management API' (for read/write access), or 'Preview API' (for read-only access to draft content).
    • Access Level: For CMA tokens, specify the read/write permissions for models and fields. For CDA/Preview tokens, access is typically read-only.
    • Environments: Select which environments the token should have access to (e.g., 'main', 'staging').
  5. Generate and Copy Token: After configuring, generate the token and copy it immediately. DatoCMS typically shows the token only once upon creation for security reasons. Store it securely.

It is crucial to generate separate tokens for different applications or environments to adhere to the principle of least privilege. For instance, a front-end application retrieving published content should only use a read-only Content Delivery API token, while a build script that publishes content might require a Content Management API token with appropriate write permissions.

Authenticated request example

Authenticating requests to DatoCMS APIs involves including your API token in the Authorization header with the Bearer scheme. The following examples demonstrate how to make an authenticated request using common programming languages and tools.

Content Delivery API (CDA) with GraphQL (JavaScript)

The DatoCMS Content Delivery API primarily uses GraphQL for content retrieval. Here's an example using JavaScript's fetch API to query published articles:

const API_TOKEN = 'YOUR_READ_ONLY_CDA_TOKEN';
const QUERY = `
  query AllArticles {
    allArticles {
      id
      title
      slug
    }
  }
`;

fetch('https://graphql.datocms.com/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': `Bearer ${API_TOKEN}`,
  },
  body: JSON.stringify({ query: QUERY }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching articles:', error));

Content Management API (CMA) with REST (Ruby)

The DatoCMS Content Management API offers a REST interface for managing content. This Ruby example demonstrates creating a new record using the CMA:

require 'net/http'
require 'uri'
require 'json'

API_TOKEN = 'YOUR_READ_WRITE_CMA_TOKEN'
MODEL_ID = 'YOUR_MODEL_ID' # e.g., 'article'

uri = URI.parse("https://site-api.datocms.com/items")
request = Net::HTTP::Post.new(uri.request_uri)
request["Authorization"] = "Bearer #{API_TOKEN}"
request["Content-Type"] = "application/json"
request["Accept"] = "application/json"

payload = {
  data: {
    type: "item",
    attributes: {
      title: "My New Article",
      slug: "my-new-article",
      # ... other fields
    },
    relationships: {
      item_type: {
        data: {
          type: "item_type",
          id: MODEL_ID
        }
      }
    }
  }
}.to_json

request.body = payload

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
  http.request(request)
end

puts response.body

For more examples across different languages and detailed API specifications, refer to the official DatoCMS Content Delivery API documentation and Content Management API documentation.

Security best practices

Implementing strong security practices when working with DatoCMS API tokens is critical to protect your content and prevent unauthorized access. Adhering to these guidelines helps maintain the integrity and confidentiality of your data.

  • Use Environment Variables: Never hardcode API tokens directly into your application's source code. Instead, use environment variables to store and retrieve tokens, especially in production environments. This prevents tokens from being exposed in version control systems. Services like Google Cloud's Secret Manager or AWS Secrets Manager offer secure ways to handle sensitive credentials.
  • Principle of Least Privilege: Grant API tokens only the minimum necessary permissions. For example, a front-end application displaying published content should only use a read-only Content Delivery API token. A token used for automated content publishing should have write access only to the specific models it needs to update.
  • Regular Rotation of Tokens: Periodically rotate your API tokens. This practice reduces the window of opportunity for an attacker if a token is compromised. Establish a schedule for token rotation and automate the process where possible.
  • Restrict Access by IP Address (if available): If your DatoCMS plan or proxy setup allows, restrict API token usage to a whitelist of trusted IP addresses. This adds an extra layer of security, ensuring that requests originating from unauthorized locations are rejected.
  • Monitor API Usage: Regularly monitor your API logs for unusual activity or excessive requests. Anomalies could indicate a compromised token or an attempted attack.
  • Secure Client-Side Implementations: For client-side applications (e.g., single-page applications), use Content Delivery API tokens that are read-only and have no write permissions. While these tokens are exposed in the browser, their limited scope significantly reduces the risk of a breach. Never expose Content Management API tokens (which have write access) in client-side code.
  • Use HTTPS: All communication with DatoCMS APIs occurs over HTTPS, ensuring that data and API tokens are encrypted in transit. Always verify that your API requests are made over a secure connection.
  • Avoid Public Repositories: Ensure that API tokens and sensitive configuration files are not committed to public version control repositories like GitHub. Utilize .gitignore files to exclude these from your repository.
  • Webhooks Security: If using DatoCMS webhooks, implement signature verification to ensure that incoming webhook payloads genuinely originate from DatoCMS and have not been tampered with. The DatoCMS documentation on securing webhooks provides guidance on this.