HIGH denial of serviceexpressbearer tokens

Denial Of Service in Express with Bearer Tokens

Denial Of Service in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability

A Denial of Service (DoS) risk in an Express API that uses Bearer Tokens arises when endpoint behavior depends on token validation but does not limit the cost or rate of unauthenticated or token-failed requests. In a black-box scan, middleBrick tests the unauthenticated attack surface and checks whether the API enforces rate limiting before performing expensive operations such as token introspection, signature verification, or payload parsing.

When Bearer Tokens are accepted but not validated early and efficiently, an attacker can send many malformed or missing tokens, causing the server to repeatedly attempt cryptographic verification or database lookups. This consumes CPU and memory, increasing latency for legitimate users and potentially exhausting resources. The same risk is higher when the API parses large or deeply nested JSON payloads before rejecting a request due to an invalid token, which combines BFLA/Privilege Escalation concerns with DoS through resource-heavy request processing.

Because middleBrick runs 12 security checks in parallel, it evaluates whether Rate Limiting is applied before authentication and token validation. Without pre-authentication rate limits, an API may allow many token-verification attempts per second, enabling token brute-force or resource exhaustion. DoS findings in this context are often tied to missing Input Validation, excessive payload sizes, or missing throttling on token-introspection endpoints. The scanner also checks whether Data Exposure occurs when error messages or stack traces leak details about token validation logic under load, which can aid an attacker in crafting more effective DoS probes.

In OpenAPI/Swagger analysis, middleBrick resolves all $ref definitions and cross-references runtime behavior with the spec. If a path security scheme is defined as bearerAuth but the server does not enforce strict request-size limits or schema validation before token checks, the spec may declare security while the implementation remains vulnerable. This mismatch between documented Bearer Token requirements and actual runtime behavior can result in inconsistent protection levels and increased DoS surface.

Bearer Tokens-Specific Remediation in Express — concrete code fixes

To reduce DoS risk when using Bearer Tokens in Express, apply validation and rate limiting before performing token-intensive operations. Use middleware that checks request size and validates token format early, and enforce rate limits on authentication and token-introspection endpoints.

// Express middleware to enforce early Bearer Token validation and rate limiting
const rateLimit = require('express-rate-limit');
const jwt = require('jsonwebtoken');

// 1) Apply a strict rate limit to all endpoints, with lower limits for token validation paths
const apiLimiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 60, // limit each IP to 60 requests per windowMs
  standardHeaders: true,
  legacyHeaders: false,
});

// 2) Apply to app or specific router
app.use('/api', apiLimiter);

// 3) Early token validation and size limiting before expensive logic
app.use((req, res, next) => {
  // Limit request body size to mitigate resource exhaustion
  if (req.body && typeof req.body === 'object' && JSON.stringify(req.body).length > 10000) {
    return res.status(413).json({ error: 'Payload too large' });
  }

  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Authorization header required' });
  }

  const token = authHeader.split(' ')[1];
  if (!token || token.length > 4096) {
    return res.status(400).json({ error: 'Invalid token' });
  }

  try {
    // Perform verification only after basic checks
    const decoded = jwt.verify(token, process.env.JWT_PUBLIC_KEY, { algorithms: ['RS256'] });
    req.user = decoded;
    return next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
});

// Define routes that require valid tokens after early checks
app.get('/api/secure', (req, res) => {
  res.json({ message: 'Access granted', user: req.user });
});

For broader protection, apply per-route limits to endpoints that perform token introspection or database lookups, and ensure error handling does not expose stack traces or internal paths. middleBrick’s CLI and Web Dashboard can be used to verify that these mitigations reduce the DoS risk score and that Rate Limiting appears before authentication checks in the scan results.

When using the GitHub Action, set a security score threshold so that builds fail if the API’s risk score degrades due to missing rate limits or oversized payload handling. The MCP Server in your IDE can provide inline guidance while you develop, helping you maintain secure token handling patterns without disrupting your workflow.

Related CWEs: resourceConsumption

CWE IDNameSeverity
CWE-400Uncontrolled Resource Consumption HIGH
CWE-770Allocation of Resources Without Limits MEDIUM
CWE-799Improper Control of Interaction Frequency MEDIUM
CWE-835Infinite Loop HIGH
CWE-1050Excessive Platform Resource Consumption MEDIUM

Frequently Asked Questions

How does middleBrick test for DoS risks related to Bearer Token validation?
middleBrick sends requests without tokens and with many invalid tokens to check whether rate limits are enforced before expensive token verification or payload parsing. It also analyzes the OpenAPI spec for security definitions and compares them with runtime behavior to identify missing throttling or oversized payload handling.
Can the free plan be used to monitor DoS risk for an Express API with Bearer Tokens?
Yes, the Free plan provides 3 scans per month, which is suitable for periodic checks of an Express API’s DoS risk profile. For continuous monitoring and CI/CD integration, the Pro plan includes scheduled scans and alerts.