Authentication overview
Strapi provides mechanisms to secure its content API and administrative panel, ensuring that only authorized users and applications can access or modify data. The core of Strapi's authentication system revolves around stateless tokens, which allow for scalable and distributed API access. This approach is particularly suited for headless architectures where the backend API serves various frontend applications.
For programmatic access to the content API, Strapi primarily utilizes two methods: JSON Web Tokens (JWT) for user-based authentication and API tokens for application-level access. The choice between these methods depends on the use case, with JWTs being ideal for authenticated user sessions and API tokens for server-to-server communication or static site generation.
The built-in Users & Permissions Plugin in Strapi allows administrators to define roles and assign specific permissions to different types of users or public access. This granular control extends to individual content types and fields, enabling precise management of who can read, create, update, or delete data. Understanding these foundational elements is key to implementing secure and efficient Strapi applications.
Supported authentication methods
Strapi supports several authentication methods, each designed for specific scenarios and security requirements. The primary methods include JWT for user authentication and API tokens for programmatic access without a specific user context.
JSON Web Tokens (JWT)
JWTs are a compact, URL-safe means of representing claims to be transferred between two parties. In Strapi, JWTs are used to authenticate individual users. When a user successfully logs in (via email/password or a third-party provider), Strapi generates a JWT. This token is then returned to the client and must be included in the Authorization header of subsequent requests as a Bearer token. The token contains claims about the user and is signed, allowing the Strapi server to verify its authenticity and integrity without needing to query a database for each request, as described in the IETF RFC 7519 for JSON Web Token specification.
- When to use: User login sessions, mobile applications, single-page applications (SPAs) where users interact directly with the Strapi API.
- Security level: High, relies on cryptographic signing to prevent tampering. Token expiration adds another layer of security.
API Tokens
API tokens in Strapi provide a simple and robust way to grant applications or services access to the content API without associating the request with a specific user. These tokens are long-lived and can be configured with specific permissions and access types (e.g., read-only, full access) for particular content types. They are suitable for scenarios where a backend service or a static site generator needs to fetch data from Strapi.
- When to use: Server-side applications, static site generators, webhooks, integrations with other services.
- Security level: Moderate to High, depending on the token's scope and how it is stored. Requires careful management to prevent exposure.
Password (for Admin Panel)
The Strapi administration panel uses a traditional email/password authentication system for administrators and other backend users. This is separate from the content API authentication and is managed through the built-in user interface.
- When to use: Accessing the Strapi admin interface for content management, user management, and plugin configuration.
- Security level: Standard, relies on strong passwords and secure connection (HTTPS).
Third-Party Authentication (via Plugins)
Strapi can be extended with plugins to support third-party authentication providers like Google, GitHub, or OAuth 2.0 services. The Users & Permissions plugin documentation details how to configure various providers.
- When to use: Enhancing user experience by allowing logins with existing accounts, integrating with enterprise SSO solutions.
- Security level: Varies by provider, generally high as it leverages established identity providers.
Here's a summary table of Strapi's authentication methods:
| Method | When to Use | Security Considerations |
|---|---|---|
| JSON Web Token (JWT) | User-facing applications (SPAs, mobile apps) | Short-lived, signed, requires secure storage on client |
| API Tokens | Server-to-server communication, static site generation | Long-lived, configurable permissions, requires secure server-side storage |
| Password (Admin Panel) | Strapi administration interface access | Strong password policies, HTTPS required |
| Third-Party Auth (Plugins) | Social logins, OAuth/SSO integration | Relies on external IdP security, streamlines user experience |
Getting your credentials
The process for obtaining authentication credentials in Strapi varies depending on the method you intend to use.
For JWT (User Authentication)
- User Registration: Users must first register an account with your Strapi application. This can be done via a public registration endpoint (if enabled) or by an administrator creating the user.
- Login Request: Once registered, a user can send a POST request to the
/api/auth/localendpoint with their email and password. - Token Reception: Upon successful login, Strapi responds with a JWT in the
jwtfield. This token is your credential for authenticated requests. The Strapi REST API documentation on authentication provides example login requests.
For API Tokens
- Access Admin Panel: Log in to your Strapi administration panel.
- Navigate to API Tokens: Go to Settings > API Tokens.
- Create New API Token: Click on "Create new API Token".
- Configure Token: Provide a name, description, and select the token's type (e.g., Read-only, Full access, Custom). Custom access allows you to define granular permissions for specific content types.
- Generate Token: Save the token. Strapi will display the generated token once. Copy this token immediately as it will not be shown again for security reasons. The Strapi user documentation for API Tokens offers a step-by-step guide.
For Admin Panel Access
Your admin panel credentials (email and password) are set during the initial setup of your Strapi project or created by another administrator.
Authenticated request example
Once you have obtained your JWT or API token, you can use it to make authenticated requests to your Strapi API. The token should be included in the Authorization header of your HTTP requests.
Using a JWT (User Authentication)
After a user logs in and receives a JWT, subsequent requests would look like this:
GET /api/articles
Authorization: Bearer <YOUR_JWT_TOKEN>
Content-Type: application/json
fetch('http://localhost:1337/api/articles', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${yourJwtToken}`
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Using an API Token
For API token authentication, the structure is similar:
GET /api/products
Authorization: Bearer <YOUR_API_TOKEN>
Content-Type: application/json
fetch('http://localhost:1337/api/products', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${yourApiToken}`
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Security best practices
Implementing robust authentication is only one part of securing your Strapi application. Adhering to security best practices is crucial to protect your data and endpoints.
Token Management
- Store tokens securely: For JWTs in client-side applications, avoid storing them in
localStoragedue to XSS vulnerabilities. Consider usingHttpOnlycookies or in-memory storage for short durations. For API tokens, always store them on the server side (e.g., environment variables, secret management services) and never expose them in client-side code or public repositories. - Rotate API tokens: Periodically generate new API tokens and revoke old ones, especially if there's any suspicion of compromise.
- Set appropriate JWT expiration: Configure JWTs with reasonable expiration times to limit the window of opportunity for attackers if a token is compromised. Implement refresh token mechanisms for seamless user experience without excessively long-lived access tokens.
Access Control and Permissions
- Principle of Least Privilege: Grant only the minimum necessary permissions to users and API tokens. For example, if an application only needs to read articles, provide it with a read-only API token for the 'article' content type.
- Define Roles: Utilize Strapi's Users & Permissions plugin to define distinct roles (e.g., authenticated, public, editor, admin) and assign specific permissions to each role for every content type.
- Public Access Control: Carefully review and restrict public access permissions. By default, Strapi allows public access to certain endpoints. Ensure that only data intended for public consumption is exposed without authentication.
Application and Infrastructure Security
- Use HTTPS: Always enforce HTTPS for all communication with your Strapi API and admin panel to encrypt data in transit and prevent eavesdropping. This is a fundamental web security practice, detailed by the Google Search Central HTTPS migration guide.
- Input Validation: Implement robust input validation on all data received by your API to prevent common vulnerabilities like SQL injection and cross-site scripting (XSS). While Strapi provides some built-in protection, custom logic may require additional validation.
- Keep Strapi Updated: Regularly update your Strapi instance and its plugins to the latest versions to benefit from security patches and bug fixes.
- Environment Variables: Store sensitive configurations, such as database credentials and application secrets, in environment variables rather than hardcoding them directly in your application code.
- Rate Limiting: Implement rate limiting on authentication endpoints to mitigate brute-force attacks against user credentials.
- Monitoring and Logging: Set up monitoring and logging for authentication attempts and API access to detect and respond to suspicious activities.