HIGH api rate abusestrapibearer tokens

Api Rate Abuse in Strapi with Bearer Tokens

Api Rate Abuse in Strapi with Bearer Tokens — how this combination creates or exposes the vulnerability

Rate abuse in Strapi when Bearer Tokens are used centers on how authenticated endpoints are treated by the API and by scanners. Strapi’s default behavior for routes protected by an API token or a custom JWT/Bearer scheme is to accept requests that include a valid token in the Authorization header. If rate limiting is not explicitly configured for these authenticated routes, an attacker who obtains a single valid Bearer Token can make a high volume of requests without being challenged by IP-based controls, because the token identifies an authorized user or service.

In a black-box scan, middleBrick tests authenticated attack surfaces by including Bearer Tokens where the API expects them. Without per-user or per-token rate limiting, an attacker can iterate over user IDs (BOLA/IDOR) or trigger resource-intensive operations, consuming server-side rate budgets that are intended to protect unauthenticated paths. Strapi’s admin and plugin configurations sometimes apply global limits but omit token-aware policies, allowing abuse via compromised or leaked tokens. Common real-world patterns include using a single service account token shared across microservices or CI jobs, which increases the blast radius if the token is exposed.

Real attack patterns tied to this combination involve credential leakage in logs or client-side code, token reuse across environments, and missing decoupling of authentication and authorization checks. For example, an endpoint like GET /api/articles/:id that relies on a Bearer Token but lacks token-specific counters can be hammered to enumerate valid article IDs (IDOR) or exhaust backend worker concurrency. Because Strapi can serve both public and authenticated routes under the same path prefix, misconfigured middleware may apply limits only to unauthenticated traffic, leaving authenticated channels open to sustained abuse.

middleBrick’s 12 security checks run in parallel and include Rate Limiting and Authentication, which together surface cases where Bearer Token authenticated endpoints lack adequate throttling. The scanner reports findings with severity and remediation guidance, mapping observations to frameworks such as OWASP API Top 10 and highlighting risks like excessive data exposure when enumeration occurs via authenticated channels.

Bearer Tokens-Specific Remediation in Strapi — concrete code fixes

To remediate rate abuse for Bearer Token authenticated endpoints in Strapi, apply token-aware rate limiting and tighten token handling in your Strapi project. Below are concrete, syntactically correct examples you can adapt to your Strapi project using policies and middleware.

1. Token-aware rate limiting via custom policy

Create a custom policy that reads the Bearer Token and enforces limits per token. This ensures that each token has its own quota rather than relying only on IP-based limits.

// src/api/rate-limit-policy/policy.js
'use strict';

const rateLimit = require('koa-ratelimit');
const { getConnection } = require('strapi-utils');

module.exports = async (ctx, next) => {
  const auth = ctx.request.header.authorization || '';
  const token = auth.startsWith('Bearer ') ? auth.slice(7) : null;

  // Fallback to IP when no token is present (defense in depth)
  const key = token || ctx.ip;

  const limiter = rateLimit({
    store: getConnection().store || 'memory', // replace with Redis store in production
    duration: 60 * 1000, // 1 minute
    max: token ? 300 : 100, // stricter for authenticated tokens
    message: { error: 'Too many requests, please try again later.' }
  });

  return limiter(ctx, next);
};

Register the policy in src/policies/config/policies.json and assign it to the routes that require token-based protection, for example the content API routes.

2. Scoping tokens to users and enforcing per-user limits

If your Bearer Tokens represent users or service accounts, scope limits by user ID extracted from the token payload. Below is an example using a JWT-style token; adapt the extraction to your token format.

// src/api/user-rate-limit-policy/policy.js
'use strict';

const jwt = require('jsonwebtoken');

module.exports = async (ctx, next) => {
  const auth = ctx.request.header.authorization || '';
  const token = auth.startsWith('Bearer ') ? auth.slice(7) : null;

  if (!token) {
    ctx.status = 401;
    ctx.body = { error: 'Unauthorized' };
    return;
  }

  let payload;
  try {
    payload = jwt.verify(token, process.env.JWT_SECRET || 'your-secret');
  } catch (err) {
    ctx.status = 401;
    ctx.body = { error: 'Invalid token' };
    return;
  }

  const userId = payload.sub || payload.userId;
  if (!userId) {
    ctx.status = 401;
    ctx.body = { error: 'Token missing user identifier' };
    return;
  }

  // Apply per-user rate limit using a Redis-backed store
  const rateLimit = require('koa-ratelimit');
  const { getConnection } = require('strapi-utils');

  await rateLimit({ 
    store: getConnection().store || 'memory',
    key: `user:${userId}`,
    duration: 60 * 1000,
    max: 200,
    message: { error: 'User rate limit exceeded' }
  })(ctx, next);
};

3. Example Bearer Token usage in Strapi requests

When calling Strapi endpoints from clients or services, include the token consistently and avoid leaking it in URLs or logs.

// Example using fetch in Node.js
const fetch = require('node-fetch');

const BEARER_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTY5ODgwMDAwMH0.exampleSignature';

async function fetchArticle(id) {
  const res = await fetch(`http://localhost:1337/api/articles/${id}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${BEARER_TOKEN}`
    }
  });
  const data = await res.json();
  console.log(data);
}

fetchArticle(1).catch(console.error);

4. Operational practices

Rotate Bearer Tokens regularly, avoid sharing a single token across environments, and monitor logs for repeated failed authentication or high request volume from a single token. Combine token-based rate limits with Strapi’s built-in protections such as admin route restrictions and secure cookie settings.

Frequently Asked Questions

Does middleBrick fix rate abuse findings in Strapi?
middleBrick detects and reports rate abuse findings with severity and remediation guidance; it does not fix, patch, or block. Follow the remediation guidance to adjust policies and limits in Strapi.
Can Bearer Tokens be used safely with Strapi if rate limits are applied?
Yes, Bearer Tokens can be used safely when combined with token-aware rate limits, proper token rotation, and scoped permissions. Use token-specific limits and avoid sharing tokens across services.