Authentication overview

Medusa, designed as a developer-first headless commerce platform, enforces authentication to secure its various API endpoints. This ensures that only authorized clients and users can access sensitive data and perform operations such as managing products, processing orders, or retrieving customer information. Medusa separates authentication concerns for its Storefront API and Admin API, reflecting the different access levels and security requirements for customer-facing operations versus backend administration.

For storefront interactions, Medusa typically uses a combination of API tokens for public data access and JSON Web Tokens (JWTs) for authenticated customer sessions. The Admin API, conversely, relies on JWTs issued upon successful login by an administrative user, granting access to the full suite of backend management functionalities. This tiered approach to authentication helps maintain a robust security posture across the entire commerce ecosystem.

Understanding the distinction between these authentication mechanisms is crucial for developers building on Medusa. Proper implementation ensures data integrity, protects customer privacy, and prevents unauthorized access to administrative controls. Medusa's API reference documentation provides comprehensive details on required headers and authentication flows for each endpoint.

Supported authentication methods

Medusa supports several primary authentication methods tailored to different use cases within its headless commerce architecture. The choice of method depends on whether the interaction is with the Storefront API or the Admin API, and the level of access required.

The Storefront API is designed for public storefronts and customer-facing applications. It uses:

  • Publishable API Keys: These keys provide read-only access to public data, such as product listings and collections. They are generally safe to expose in client-side applications.
  • Customer JSON Web Tokens (JWTs): Once a customer logs in or registers, Medusa issues a JWT (specifically, an access_token and optionally a refresh_token). This token grants authenticated access to customer-specific data, such as order history, profile information, and the ability to place orders. These tokens are typically sent in the Authorization header as a Bearer token.

The Admin API is exclusively for administrative users and backend applications that manage the commerce platform. It uses:

  • Admin JSON Web Tokens (JWTs): Upon successful login by an administrative user, Medusa issues an Admin JWT. This token provides extensive write and read access to all administrative functions, including product management, order fulfillment, and user management. Admin JWTs are highly sensitive and must be securely stored and transmitted.

Medusa's modular nature also allows for the integration of third-party authentication solutions through plugins. Developers can extend Medusa's core functionality to support alternative identity providers or OAuth flows if required, though the built-in JWT and API key mechanisms cover most standard commerce scenarios. For example, plugins can facilitate OAuth 2.0 based authentication for social logins or enterprise SSO solutions.

Authentication Method Comparison

Method When to Use Security Level
Publishable API Key Accessing public storefront data (e.g., product listings) from client-side. Low (read-only, public data)
Customer JWT Authenticated customer sessions (e.g., viewing orders, checkout) in storefronts. Medium (scoped to individual customer)
Admin JWT Admin dashboard access, backend integrations requiring full administrative control. High (full administrative access)

Getting your credentials

Accessing Medusa's APIs requires obtaining the appropriate credentials. The process varies slightly depending on the type of API and the authentication method you intend to use.

For Storefront API (Publishable API Key)

  1. Generate Key in Medusa Admin: Navigate to your Medusa Admin dashboard. Under the settings or developer section, you can generate a new Publishable API Key. This key is typically associated with a sales channel, allowing you to filter products and other data specific to that channel.
  2. Configuration: Once generated, copy the key. You will configure your storefront application to use this key, usually by setting it as an environment variable (e.g., NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY for a Next.js storefront).

For Storefront API (Customer JWT)

  1. Customer Registration/Login: A customer must register or log in through your storefront application.
  2. Backend Authentication Request: Your storefront backend or a direct API call will send the customer's credentials (email/password) to the Medusa Storefront API's /store/auth or /store/customers endpoints.
  3. Token Issuance: Upon successful authentication, Medusa will return an access_token (the JWT) and potentially a refresh_token.
  4. Client-side Storage: The access_token should be stored securely on the client-side, typically in an HTTP-only cookie or in memory, for subsequent authenticated requests. The refresh_token, if used, should also be stored securely to obtain new access tokens without re-authenticating the user.

For Admin API (Admin JWT)

  1. Admin User Creation: Ensure you have an administrative user account set up in your Medusa backend. This is usually done during the initial setup of your Medusa server or via the Admin dashboard.
  2. Login Request: Make a POST request to the Medusa Admin API's /admin/auth endpoint with the administrator's email and password.
  3. Token Issuance: If the credentials are valid, Medusa will respond with an access_token (the Admin JWT) and a refresh_token.
  4. Secure Storage: This Admin JWT is highly sensitive. For client-side admin applications (like the Medusa Admin dashboard), it's typically stored in an HTTP-only cookie. For server-to-server integrations, it should be stored in a secure environment variable or a secrets management service.

For detailed instructions on setting up and managing API keys and JWTs, refer to the Medusa Storefront API Authentication documentation and Medusa Admin API Authentication documentation.

Authenticated request example

Once you have obtained the necessary authentication token, you can include it in the Authorization header of your API requests. The examples below demonstrate how to make authenticated requests to both the Storefront and Admin APIs using a Bearer token.

Storefront API Example (authenticated customer)

This example retrieves the authenticated customer's profile details using a Customer JWT.

import axios from 'axios';

const MEDUSA_STORE_URL = 'http://localhost:9000'; // Replace with your Medusa Store URL
const CUSTOMER_JWT = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'; // Replace with an actual Customer JWT

async function getCustomerProfile() {
  try {
    const response = await axios.get(`${MEDUSA_STORE_URL}/store/customers/me`, {
      headers: {
        'Authorization': `Bearer ${CUSTOMER_JWT}`,
        'Content-Type': 'application/json',
      },
    });
    console.log('Customer Profile:', response.data.customer);
  } catch (error) {
    console.error('Error fetching customer profile:', error.response ? error.response.data : error.message);
  }
}

getCustomerProfile();

Admin API Example (authenticated administrator)

This example retrieves a list of products using an Admin JWT.

import axios from 'axios';

const MEDUSA_ADMIN_URL = 'http://localhost:9000'; // Replace with your Medusa Admin URL
const ADMIN_JWT = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'; // Replace with an actual Admin JWT

async function getAdminProducts() {
  try {
    const response = await axios.get(`${MEDUSA_ADMIN_URL}/admin/products`, {
      headers: {
        'Authorization': `Bearer ${ADMIN_JWT}`,
        'Content-Type': 'application/json',
      },
    });
    console.log('Admin Products:', response.data.products);
  } catch (error) {
    console.error('Error fetching admin products:', error.response ? error.response.data : error.message);
  }
}

getAdminProducts();

In both examples, the Authorization: Bearer [TOKEN] header is crucial for authenticating the request against the Medusa backend. Remember to replace placeholder URLs and tokens with your actual Medusa instance details and valid JWTs.

Security best practices

Implementing robust security practices is paramount when handling authentication in any commerce platform. For Medusa, adherence to these principles helps protect sensitive customer and business data.

  1. Secure Credential Storage:
    • Environment Variables: Store sensitive credentials like API keys and database connection strings in environment variables, especially in production environments. Avoid hardcoding these values directly into your codebase.
    • Secrets Management: For more advanced deployments, utilize a secrets management service (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) to store and retrieve credentials securely at runtime. This practice reduces the risk of credentials being exposed in code repositories or configuration files.
    • HTTP-only Cookies: For storing JWTs on the client-side (e.g., in a web browser for a storefront or admin dashboard), use HTTP-only cookies. This prevents client-side JavaScript from accessing the cookie, mitigating certain cross-site scripting (XSS) attacks.
  2. Token Management:
    • Short-lived Access Tokens: Issue access tokens with a short expiration time. This limits the window of opportunity for an attacker if a token is compromised.
    • Refresh Tokens: Use refresh tokens to obtain new access tokens without requiring the user to re-authenticate frequently. Refresh tokens should be long-lived, stored securely (ideally in HTTP-only cookies or a secure backend), and ideally invalidated if suspicious activity is detected.
    • Token Revocation: Implement mechanisms to revoke compromised or outdated tokens immediately. For JWTs, this often involves maintaining a blacklist or a database of revoked tokens.
  3. Secure Communication (HTTPS):
    • Always enforce HTTPS for all communication with your Medusa backend. This encrypts data in transit, protecting credentials and sensitive information from interception. Tools like Cloudflare SSL certificates or Nginx with Let's Encrypt can facilitate this.
  4. Input Validation and Sanitization:
    • Validate and sanitize all user inputs, especially for login and registration forms, to prevent common web vulnerabilities like SQL injection and XSS.
  5. Rate Limiting:
    • Implement rate limiting on authentication endpoints (e.g., login, password reset) to prevent brute-force attacks.
  6. Logging and Monitoring:
    • Log all authentication attempts, both successful and failed. Monitor these logs for unusual patterns or suspicious activities that could indicate an attack.
  7. Principle of Least Privilege:
    • Grant users and applications only the minimum necessary permissions to perform their tasks. For example, a storefront application should only have access to public product data and customer-specific information, not administrative controls.

By following these best practices, developers can significantly enhance the security posture of their Medusa-powered commerce solutions, safeguarding both their platform and their users' data.