Strapi Advanced Auth — API Tokens, Webhooks, and Server-to-Server Authentication
In this tutorial, you will learn advanced authentication patterns in Strapi including API tokens for programmatic access, webhook security verification, and server-to-server authentication strategies for communication between Strapi and external services.
What You'll Learn
- How to create and manage API tokens for server-to-server access
- How to configure webhooks and verify webhook payloads
- How to implement server-to-server authentication without user involvement
- How Transfer Tokens work for data migration
- How to revoke and rotate tokens securely
- Best practices for machine-to-machine authentication
Why It Matters
Not all API consumers are human users with browsers. Background jobs, microservices, CI/CD pipelines, and external integrations need programmatic access to Strapi. These machine clients cannot log in through a browser. API tokens and webhook secrets provide secure, non-interactive authentication for these scenarios.
Real-World Use
A content aggregation service needs to fetch the latest articles from a Strapi API every hour. No user is sitting at a browser to log in. An API token with read-only access is created and stored in the aggregator's configuration. The aggregator makes authenticated requests using the token, without any user interaction.
Learning Path
flowchart LR A["SSO & OAuth"] --> B["Advanced Auth
-- You are here"]:::current B --> C["Media Upload"] C --> D["Upload Providers"] D --> E["Image Optimization"] classDef current fill:#4945ff,color:#fff,stroke-width:2px
API Tokens
API tokens are long-lived credentials for programmatic API access. They bypass user authentication and have their own permission scope.
// Creating an API token
// Settings > Administration Panel > API Tokens > Create Token
// Token configuration:
{
name: "Production Frontend",
description: "Used by the Next.js frontend server",
tokenType: "custom", // read-only, full-access, or custom
lifespan: "unlimited", // or specific duration
permissions: {
"api::article.article": ["find", "findOne"],
"api::category.category": ["find", "findOne"],
}
}
// After creation, Strapi shows the token once:
// Token: "9821ab3c4d5e6f7890ab1cd2ef3456789abcdef0123456789abcdef012345678"
// Store this securely — it cannot be retrieved later
API tokens are used like JWT tokens in API requests:
// Using an API token
const API_TOKEN = "9821ab3c4d5e6f7890ab1cd2ef3456789abcdef0123456789abcdef012345678";
const response = await fetch("http://localhost:1337/api/articles", {
headers: {
Authorization: `Bearer ${API_TOKEN}`,
},
});
The difference between API tokens and user JWTs:
| Aspect | API Token | User JWT |
|---|---|---|
| Created by | Admin panel | Login/register |
| Expires | Configurable | Configurable |
| Permission scope | Custom per token | Based on user role |
| Linked to user | No | Yes |
| Can be revoked | Yes | No (until expiration) |
| Use case | Server-to-server | User authentication |
API Token Types
Strapi offers three API token types:
// 1. Read-only token
// Can only perform GET requests (find, findOne)
// Safe for public frontend servers
// 2. Custom token
// You select exactly which endpoints and actions the token can access
// Recommended for most use cases
// 3. Full-access token
// Can perform any operation on any content type
// Use sparingly — equivalent to admin access
// Token type configuration:
{
name: "CI/CD Deploy Token",
tokenType: "custom",
permissions: {
"api::article.article": ["find", "findOne", "create", "update"],
"api::category.category": ["find", "findOne"],
}
}
Best practice: use custom tokens with the minimum permissions needed for the task. A token that only reads articles should not have permission to delete them.
Webhooks
Webhooks notify external services when content changes in Strapi.
// Configuring a webhook:
// Settings > Webhooks > Add Webhook
{
name: "Slack Notifications",
url: "https://hooks.slack.com/services/T00/B00/xxxxx",
events: [
"entry.create",
"entry.update",
"entry.delete",
"entry.publish",
"entry.unpublish",
],
headers: {
"X-Custom-Header": "value",
},
}
Webhooks send a POST request to the configured URL when the specified events occur:
// Webhook payload for entry.create
{
"event": "entry.create",
"createdAt": "2026-06-28T10:00:00.000Z",
"model": "article",
"entry": {
"id": 1,
"title": "New Article",
// ... other fields
}
}
Webhook Security
Webhooks can reveal sensitive data. Secure them with:
// 1. Using a secret token
// In the webhook configuration:
{
name: "Search Index Updater",
url: "https://api.example.com/webhooks/strapi",
headers: {
"X-Webhook-Secret": process.env.WEBHOOK_SECRET,
},
}
// 2. On the receiving end, verify the secret:
// Express.js example:
app.post("/webhooks/strapi", (req, res) => {
const secret = req.headers["x-webhook-secret"];
if (secret !== process.env.WEBHOOK_SECRET) {
return res.status(401).json({ error: "Invalid secret" });
}
// Process webhook
const { event, model, entry } = req.body;
console.log(`${event} on ${model}: ${entry.id}`);
res.status(200).end();
});
- Use HTTPS for all webhook URLs
- Validate the payload structure before processing
- Implement timeout handling and retry logic
Transfer Tokens
Transfer Tokens are used for data transfer between Strapi instances (migration, backup, sync).
// Creating a Transfer Token:
// Settings > Administration Panel > Transfer Tokens > Create Token
{
name: "Staging to Production Transfer",
tokenType: "push", // push, pull, or push-pull
lifespan: "24h",
}
// Using Transfer Tokens:
// Strapi transfer CLI
npm run strapi transfer -- --from http://localhost:1337/admin \
--to https://production.example.com/admin \
--token $TRANSFER_TOKEN
Transfer Tokens are separate from API Tokens. They are specifically for the Strapi transfer feature, which migrates content and configuration between environments.
Server-to-Server Authentication Patterns
Beyond API tokens, several patterns are useful for server-to-server communication:
// Pattern 1: API Token (simplest)
// Suitable for: Cron jobs, background workers, frontend servers
const API_TOKEN = process.env.STRAPI_API_TOKEN;
async function fetchContent() {
const response = await fetch("https://api.example.com/articles", {
headers: { Authorization: `Bearer ${API_TOKEN}` },
});
return response.json();
}
// Pattern 2: JWT with service account
// Suitable for: Microservices that need user-level permissions
// Create a "service account" user, use its JWT
// Pattern 3: Mutual TLS (mTLS)
// Suitable for: High-security environments
// Both Strapi and the client present certificates
// Pattern 4: IP whitelisting
// Suitable for: Internal services on the same network
// Restrict API access to specific IP addresses in middleware
Choose the pattern based on your security requirements and infrastructure.
Token Rotation and Revocation
Tokens should be rotated regularly and revoked immediately if compromised.
// Revoking tokens:
// Settings > Administration Panel > API Tokens
// Click the "Revoke" button on any token
// The token becomes invalid immediately
// Token rotation best practices:
// 1. Set expiration dates on tokens when possible
// 2. Rotate tokens every 90 days
// 3. Create separate tokens for each service
// 4. Monitor token usage and revoke unused tokens
// 5. Have a process for emergency token revocation
// Automated rotation script:
async function rotateToken(oldToken, newTokenName) {
// Create new token via admin API or UI
// Update all services to use the new token
// Test the new token
// Revoke the old token
// Log the rotation
}
Common Mistakes
Using full-access tokens by default. Full-access tokens can perform any operation. If compromised, an attacker has complete control. Always use custom tokens with minimum permissions.
Hardcoding tokens in source code. Commit tokens to version control and they are exposed to everyone with repository access. Use environment variables or a secrets manager.
Not validating webhook payloads. Accepting any POST to your webhook endpoint without verification allows attackers to send fake events. Always verify webhook secrets and validate payloads.
Using API tokens where user authentication is needed. API tokens are not linked to a specific user. Use user JWT for operations that need to know who performed them (audit logs, ownership checks).
Creating one token for multiple services. If a single token is used by the frontend, the background worker, and the CI/CD pipeline, revoking it breaks all three. Create separate tokens for each service.
Practice Questions
What is the difference between an API Token and a JWT? Answer: API Tokens are long-lived credentials for server-to-server access with their own permission scope. JWTs are short-lived tokens tied to a specific user's role. API Tokens are not linked to a user account.
How do you secure a webhook endpoint? Answer: Use a shared secret in the webhook headers, verify the secret on the receiving end, use HTTPS, validate the payload structure, and implement timeout handling.
What is a Transfer Token used for? Answer: Transfer Tokens authenticate data transfer between Strapi instances for migration, backup, and synchronization. They are separate from API Tokens and have their own permission types (push, pull, push-pull).
Challenge: Implement a complete server-to-server integration: (1) Create an API token with read-only access to articles and categories, (2) Write a Node.js script that runs on a cron schedule and fetches new articles using the token, (3) Configure a webhook that notifies an external service when articles are created or updated, (4) Implement webhook verification on the receiving service, (5) Create a token rotation Process that generates a new token and updates the consuming service.
FAQ
Mini Project
Your task: Build a server-to-server integration with Strapi.
- Create two API tokens: one read-only for a frontend server, one with create/update permissions for a content import script.
- Write a Node.js script that uses the import token to fetch articles from an external API and create them in Strapi.
- Configure a webhook that sends a notification to a Slack channel (or a custom endpoint) whenever an article is published.
- Implement webhook signature verification on the receiving service.
- Create a token rotation script that generates a new token, updates the consuming services, and revokes the old token.
- Document the entire setup with security considerations.
What's Next
Now that you understand advanced authentication, proceed to Media Upload to learn about uploading and managing files in Strapi. After that, explore Upload Providers for configuring cloud storage with S3, Cloudinary, and R2.
Related lessons:
- REST API Security — General API security
- Node.js Security — Security best practices
- GraphQL Security — Securing Graphql endpoints
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro