Authentication overview
Directus provides a flexible authentication system designed to secure access to its API and administrative application. The platform supports various authentication flows to accommodate different use cases, from server-to-server communication to user-facing applications and enterprise environments. Understanding these methods is crucial for implementing secure and efficient data access within Directus projects.
Authentication in Directus primarily involves verifying the identity of a client or user and subsequently granting them access based on their assigned permissions. This process ensures that only authorized entities can perform operations like reading, creating, updating, or deleting data managed by Directus. The system is built to integrate with standard security protocols, offering developers choices for how they manage access control for their content and data models.
Supported authentication methods
Directus supports several authentication methods to cater to different application requirements and security postures. These methods are designed to provide secure access to both the Directus API and the administrative user interface.
- Static Access Tokens: These are long-lived tokens that can be generated for specific users or roles. They are suitable for server-to-server communication, automated scripts, or integrations where a user session isn't required. Static tokens offer a straightforward way to authenticate programmatic access without needing to re-authenticate frequently.
- OAuth 2.0: Directus implements the OAuth 2.0 authorization framework, which allows third-party applications to obtain limited access to user accounts on an HTTP service. This is particularly useful for public-facing applications where users grant permissions without sharing their Directus credentials directly. Directus supports various OAuth 2.0 grant types, including Authorization Code, Client Credentials, and Password grants, depending on the application's needs. OAuth 2.0 is a widely adopted industry standard for delegated authorization, as detailed in the OAuth 2.0 specification.
- Single Sign-On (SSO): For enterprise environments, Directus supports SSO integrations, typically via OpenID Connect (OIDC) or SAML. SSO allows users to authenticate once with a corporate identity provider and gain access to multiple services, including Directus, without re-entering credentials. This enhances user experience and centralizes identity management. For example, Google provides guidelines for implementing OAuth 2.0 for Web Server Applications, which can be adapted for Directus.
- Email/Password: The default authentication method for the Directus administrative application. Users log in with an email address and password, which are then used to generate a session token for subsequent requests.
Authentication Method Comparison
| Method | When to Use | Security Level |
|---|---|---|
| Static Access Tokens | Server-to-server, scripts, internal tools | High (if securely stored) |
| OAuth 2.0 | Third-party applications, public clients, delegated access | High (standardized, token-based) |
| Single Sign-On (SSO) | Enterprise environments, centralized identity management | Very High (leverages IdP security) |
| Email/Password | Admin Panel access, user-facing applications | Moderate (requires strong password policies) |
Getting your credentials
The process for obtaining credentials in Directus varies depending on the chosen authentication method:
- Static Access Tokens:
- Log in to the Directus administrative application.
- Navigate to
Settings > UsersorSettings > Roles. - Select a user or role for which to generate a token.
- Under the "Access Tokens" section, create a new token.
- Copy the generated token immediately, as it may not be retrievable later.
- OAuth 2.0 Client Credentials:
- Configure an OAuth 2.0 client within Directus. This typically involves defining redirect URIs and scopes.
- Directus will provide a Client ID and Client Secret. These are essential for initiating the OAuth flow from your client application.
- Implement the OAuth 2.0 flow in your application to exchange an authorization code for an access token and refresh token.
- SSO Configuration:
- Integrate Directus with your chosen Identity Provider (IdP), such as Okta, Auth0, or Azure AD.
- Configure the necessary settings in Directus (e.g., client ID, client secret, discovery URL for OIDC, or metadata XML for SAML).
- Ensure your IdP is configured to trust Directus as a service provider.
- Email/Password (for user accounts):
- New users can be invited by an administrator through the Directus Admin Panel.
- Users set their password upon first login or through a password reset flow.
- Existing users authenticate via the login form in the Directus Admin Panel or through the API's
/auth/loginendpoint.
Authenticated request example
Once you have obtained an access token (either static or dynamic via OAuth), you can use it to authenticate your API requests. The most common method is to include the token in the Authorization header of your HTTP requests, typically using the Bearer scheme.
Here's an example using cURL to fetch items from a collection named articles, authenticated with a Static Access Token:
curl -X GET \
https://your-directus-instance.com/items/articles \
-H "Authorization: Bearer YOUR_STATIC_ACCESS_TOKEN"
For JavaScript applications using the Directus SDK, authentication is handled programmatically:
import { createDirectus, rest, staticToken } from '@directus/sdk';
const client = createDirectus('https://your-directus-instance.com').with(rest());
async function fetchArticlesWithStaticToken(token) {
const authenticatedClient = client.with(staticToken(token));
try {
const articles = await authenticatedClient.items('articles').readByQuery();
console.log(articles);
} catch (error) {
console.error('Error fetching articles:', error);
}
}
// Replace 'YOUR_STATIC_ACCESS_TOKEN' with your actual token
fetchArticlesWithStaticToken('YOUR_STATIC_ACCESS_TOKEN');
When using OAuth 2.0, after successfully completing the authorization flow, your application will receive an access token. This token is then used in the same Authorization: Bearer header format for subsequent API calls until it expires. Refresh tokens can be used to obtain new access tokens without re-authenticating the user, as described in the Directus documentation on OAuth 2.0 refresh tokens.
Security best practices
Implementing strong authentication practices is vital for maintaining the security of your Directus instance and the data it manages. Adhere to these best practices:
- Secure Token Storage: Never hardcode static access tokens directly into your application code. Use environment variables, secure configuration files, or a dedicated secret management service (e.g., AWS Secrets Manager, Google Secret Manager) to store tokens. For client-side applications, use secure HTTP-only cookies or browser storage with appropriate security headers to protect session tokens.
- Principle of Least Privilege: Assign the minimum necessary permissions to users and API tokens. For instance, a token used for reading public data should not have write or delete access. Regularly review and adjust permissions as project requirements change.
- Token Expiration and Rotation: Configure access tokens with appropriate expiration times. For OAuth 2.0, leverage refresh tokens securely to obtain new access tokens without re-authenticating the user, but ensure refresh tokens also have a reasonable lifespan and are revoked upon misuse. Regularly rotate static access tokens, especially in automated systems.
- Use HTTPS Everywhere: Always ensure all communication with your Directus instance occurs over HTTPS. This encrypts data in transit, protecting credentials and sensitive information from interception. Directus deployments should enforce SSL/TLS for all connections.
- Enable Multi-Factor Authentication (MFA): For administrative users and any user accounts with elevated privileges, enable MFA if available. This adds an extra layer of security by requiring a second form of verification beyond just a password.
- Implement Strong Password Policies: Enforce complex password requirements (minimum length, combination of character types) and encourage regular password changes for all user accounts.
- Monitor Authentication Logs: Regularly review Directus authentication logs for suspicious activity, such as repeated failed login attempts or access from unusual IP addresses. Integrate these logs with a security information and event management (SIEM) system if possible.
- Keep Directus Updated: Regularly update your Directus instance to the latest stable version. Updates often include security patches that address newly discovered vulnerabilities.
- Validate Input and Output: While authentication secures access, proper input validation and output encoding are crucial to prevent common web vulnerabilities like SQL injection and Cross-Site Scripting (XSS) within your Directus project.