HIGH api key exposurestrapibasic auth

Api Key Exposure in Strapi with Basic Auth

Api Key Exposure in Strapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Strapi is a headless CMS that often exposes administrative interfaces and API endpoints under a predictable base path such as /admin or /api. When Basic Authentication is used without additional protections, credentials are transmitted in an encoded but easily reversible form. If an API key or session token is also exposed—whether through error messages, misconfigured CORS, client-side JavaScript, or open GraphQL introspection—an attacker who captures the Basic Auth header can pair it with the leaked key to escalate privileges or access restricted data.

In a black-box scan, middleBrick tests unauthenticated surfaces and checks for information leakage across multiple vectors. For Strapi deployments using Basic Auth, the scanner inspects response differences between valid and invalid credentials, examines HTTP headers for key references, and probes for verbose error messages that may reveal keys. Because Strapi’s admin panel sometimes embeds configuration in client-side bundles, an exposed API key stored in JavaScript can be harvested and reused in combination with Basic Auth credentials to bypass intended access boundaries.

Consider an endpoint like GET /api/users/profile. If Basic Auth is accepted but the application also relies on an API key passed via an X-API-Key header, a finding may be reported if the key is derivable from the client code or returned in error detail. Attack patterns such as credential stuffing or replay can be attempted when both factors are exposed. Even if Strapi’s role-based access controls appear intact, the presence of an unprotected key effectively widens the attack surface, enabling lateral movement across authenticated contexts.

middleBrick’s checks include input validation, authentication mechanisms, and property authorization. When scanning Strapi with Basic Auth, the tool examines whether authentication headers are transmitted over encrypted transport, whether credentials are cached insecurely in the browser, and whether per-request keys are leaked in URLs or logs. These checks map to common weaknesses enumerated in the OWASP API Security Top 10, including excessive data exposure and broken authentication.

Because Basic Auth sends credentials on each request, any additional leaked key multiplies the risk. An attacker who obtains both can craft authenticated requests to sensitive Strapi endpoints, potentially extracting user data or modifying content depending on assigned roles. Continuous monitoring and secure handling of both credentials and keys are required to reduce the likelihood of successful compromise.

Basic Auth-Specific Remediation in Strapi — concrete code fixes

To reduce risk, ensure that Basic Authentication is only accepted over TLS and that no keys are embedded in client-side code. Strapi’s configuration should enforce strict CORS rules and avoid verbose error messages that disclose keys or stack traces. The following examples illustrate secure implementation patterns.

Example 1: Configure Strapi to require Basic Auth for admin routes while enforcing HTTPS. Strapi’s middleware settings can be adjusted in the server configuration to reject unencrypted traffic and to scope authentication to specific paths.

// ./src/middlewares/basicAuth.js
module.exports = (config, { strapi }) => {
  return async (ctx, next) => {
    const isAdmin = ctx.path.startsWith('/admin');
    if (isAdmin) {
      const auth = ctx.request.header.authorization || '';
      if (!auth.startsWith('Basic ')) {
        ctx.status = 401;
        ctx.body = { error: 'Unauthorized' };
        return;
      }
      const decoded = Buffer.from(auth.slice(6), 'base64').toString('utf8');
      const [user, pwd] = decoded.split(':');
      const validUser = strapi.config.get('plugin.users.basic.user');
      const validPwd = strapi.config.get('plugin.users.basic.password');
      if (user !== validUser || pwd !== validPwd) {
        ctx.status = 403;
        ctx.body = { error: 'Forbidden' };
        return;
      }
    }
    await next();
  };
};

Example 2: Apply the middleware selectively and ensure CORS does not expose keys to untrusted origins. This snippet shows how to register the middleware and tighten CORS settings in Strapi’s configuration.

// ./src/middlewares/index.js
module.exports = [ 'basicAuth' ];

// ./src/config/security.js
module.exports = {
  cors: {
    enabled: true,
    origin: [ 'https://your-trusted-domain.com' ],
    headers: [ 'Authorization', 'Content-Type' ],
    exposeHeaders: [],
    credentials: true,
  },
  admin: {
    auth: {
      secret: process.env.ADMIN_JWT_SECRET,
    },
  },
};

Example 3: Rotate keys regularly and avoid storing them in environment files that are checked into version control. Use runtime injection and restrict file permissions to prevent unauthorized reads.


# .env (ensure this file is not committed)
NODE_ENV=production
BASIC_AUTH_USER=api_reader
BASIC_AUTH_PASSWORD=Super$ecureP@ssw0rd2025

In addition to these code-level changes, leverage middleBrick’s dashboard and CLI to verify that no API keys appear in client-side responses and that Basic Auth headers are not accepted over unencrypted channels. The CLI can be run locally with middlebrick scan <url> to obtain a security risk score and prioritized findings. For teams managing many endpoints, the Pro plan enables continuous monitoring and CI/CD integration, allowing scans on a schedule and blocking merges if risk thresholds are exceeded.

Frequently Asked Questions

Can Basic Auth alone protect sensitive Strapi endpoints?
No. Basic Auth should be combined with TLS, strict CORS, and secure key management. Any additional exposed credential, such as an API key, can undermine the protection provided by Basic Auth.
How can I verify that no API keys are leaked in client-side code?
Use middleBrick’s unauthenticated scan to detect references to keys in responses, and review built JavaScript bundles for hardcoded secrets. Remediate by moving keys to server-side environment variables and tightening access controls.