HIGH api key exposurestrapioauth2

Api Key Exposure in Strapi with Oauth2

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

Strapi is a headless CMS that often exposes administrative endpoints and GraphQL/HTTP APIs to clients. When Oauth2 is used for authorization, developers sometimes expose API keys or client secrets in frontend JavaScript, mobile bundles, or misconfigured server-side integrations. These keys can be leaked through source code repositories, public package managers, or client-side debugging tools. middleBrick scans for exposed keys by analyzing unauthenticated endpoints, OpenAPI specs, and runtime responses, identifying references to tokens or secrets that should remain server-side.

Oauth2 introduces specific risks when access tokens are improperly handled. For example, if a Strapi backend issues tokens with broad scopes and the client stores them insecurely (e.g., in localStorage), an attacker can steal these tokens and impersonate privileged users. middleBrick’s LLM/AI Security checks probe for token leakage in error messages or logs, which can complement the exposure of API keys used for service-to-service communication. When an OpenAPI spec includes security schemes that reference bearer tokens but runtime endpoints return keys or secrets in plaintext, the discrepancy is flagged as a high-risk finding.

Another common pattern is the use of client credentials flow in server-side integrations where Strapi acts as a resource server. If the client secret is embedded in build scripts or environment variables that are accidentally committed, middleBrick’s scan can detect these secrets in repository-derived endpoints or during dynamic probing. Because Strapi allows custom controllers and policies, developers might inadvertently create endpoints that return configuration containing API keys when accessed without proper Oauth2 enforcement. The scanner cross-references the spec’s defined flows with actual responses to identify missing protections, such as missing token validation or overly permissive CORS rules that enable token exfiltration.

During a scan, middleBrick tests unauthenticated surfaces to see whether API keys are exposed through introspection endpoints, misconfigured routes, or verbose error responses. For Oauth2-protected endpoints, it checks whether tokens are transmitted insecurely or whether the server reveals scope information that could aid an attacker. These checks are performed in parallel with other security assessments, including Input Validation and Data Exposure, to provide a comprehensive risk score and prioritized remediation guidance.

Oauth2-Specific Remediation in Strapi — concrete code fixes

To secure Strapi with Oauth2, ensure tokens are never exposed to the client-side and that all endpoints validate credentials properly. Use the password or authorization code flow for user-facing applications, and keep client secrets on the server. The following examples demonstrate secure Oauth2 configurations and token handling in Strapi.

First, configure Strapi to use a trusted Oauth2 provider without exposing keys. In your Strapi admin panel or server code, set up the provider with only public identifiers, and store secrets in server-side environment variables:

// config/plugins.js
module.exports = {
  oauth2: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorizationCallbackURL: 'https://api.example.com/connect/google/callback',
    },
  },
};

Second, protect sensitive endpoints by validating access tokens in custom policies. Create a policy that verifies the token with the Oauth2 provider and checks scopes before allowing access:

// api/protected-content/policies/validate-oauth2.js
module.exports = async (ctx, next) => {
  const authHeader = ctx.request.header.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    ctx.throw(401, 'Unauthorized: Missing bearer token');
  }
  const token = authHeader.split(' ')[1];
  try {
    // Verify token with Oauth2 provider (pseudo-code)
    const isValid = await verifyTokenWithProvider(token);
    if (!isValid) {
      ctx.throw(403, 'Forbidden: Invalid token');
    }
    // Optionally enforce scopes
    const scopes = getScopesFromToken(token);
    if (!scopes.includes('read:content')) {
      ctx.throw(403, 'Forbidden: Insufficient scope');
    }
    await next();
  } catch (error) {
    ctx.throw(401, 'Unauthorized: Invalid token');
  }
};

async function verifyTokenWithProvider(token) {
  // Implementation depends on your Oauth2 provider
  return true; // simplified
}

function getScopesFromToken(token) {
  // Decode JWT or introspect token as needed
  return ['read:content'];
}

Third, avoid returning API keys or secrets in responses. Ensure Strapi controllers do not include sensitive configuration in JSON outputs:

// api/article/controllers/article.js
'use strict';

module.exports = {
  async find(ctx) {
    const articles = await strapi.entityService.findMany('api::article.article', {
      filters: ctx.query.filters,
      pagination: ctx.query.pagination,
      populate: ['author'],
    });
    // Explicitly exclude internal fields
    return articles.map(article => ({
      id: article.id,
      title: article.title,
      publishedAt: article.publishedAt,
    }));
  },
};

Finally, enforce HTTPS and use secure cookie attributes if sessions are involved. In production configurations, set the secure flag and use SameSite attributes to mitigate token leakage over insecure channels. Regularly rotate client secrets and monitor logs for anomalous token usage patterns that could indicate compromise.

Frequently Asked Questions

How does middleBrick detect exposed API keys in Strapi endpoints?
middleBrick scans OpenAPI specs for references to keys or secrets and tests unauthenticated endpoints for verbose error messages or misconfigured routes that might leak sensitive information.
Can middleBrick check if Oauth2 tokens are stored securely in client-side code?
middleBrick’s scans focus on server-side and API behaviors; it flags patterns where tokens or secrets appear in responses or specs, but it does not analyze frontend source code storage mechanisms directly.