HIGH jwt misconfigurationexpressapi keys

Jwt Misconfiguration in Express with Api Keys

Jwt Misconfiguration in Express with Api Keys — how this specific combination creates or exposes the vulnerability

JWT misconfiguration in an Express API that also uses API keys can compound authorization risks and expose endpoints that should be protected by both factors. When JWTs are not validated strictly (e.g., missing signature verification, weak algorithms, or missing audience/issuer checks) and API keys are handled inconsistently (e.g., accepted from multiple sources or logged inadvertently), the attack surface expands. For example, an API key might be accepted as a bearer token or query parameter without proper scope checks, while JWT validation is partially implemented, allowing a threat actor to leverage a weak JWT in contexts where an API key is also accepted.

Consider an Express route that checks for an API key in a header but also parses a JWT from an Authorization header without enforcing strict algorithms or required claims. If the JWT validation defaults to none or uses a weak secret, an attacker can craft a valid-looking token that bypasses intended authorization checks. The API key mechanism may further expose the endpoint if it is accepted from headers, cookies, or query strings without canonicalization, enabling token swapping or privilege escalation. Such combinations can facilitate IDOR when identifiers in JWTs are not reconciled with API key scopes, and BOLA vulnerabilities may arise when object-level access decisions rely solely on JWT subject claims without cross-checking API key permissions.

These issues map to OWASP API Top 10 categories such as Broken Object Level Authorization (BOLA) and Security Misconfiguration. Inadequate JWT practices like using HS256 when RS256 is required, failing to validate the iss and aud claims, or not setting short expirations can allow token replay or impersonation. When API keys are accepted in insecure locations (e.g., query parameters) or without rate limiting, leaked keys can be reused alongside compromised JWTs, increasing the impact of exposure. Runtime scanning with middleBrick can surface these misconfigurations by correlating unauthenticated and authenticated-like probes, highlighting mismatches between spec-defined security schemes and runtime behavior, including discrepancies in how API keys and JWTs are consumed.

Api Keys-Specific Remediation in Express — concrete code fixes

Remediation centers on strict validation, canonicalization of where API keys are accepted, and clear separation of concerns between JWTs and API keys. Always prefer header-based API key transmission and avoid query parameters to reduce logging and leakage risks. Validate JWTs using a robust library, enforce strong algorithms, and verify claims. Below are concrete Express examples that demonstrate secure handling.

First, define a middleware that validates API keys against a known set and ensures they are provided only via headers. This prevents accidental exposure in URLs or logs and establishes a canonical source for the key.

const apiKeys = new Set(['s3cr3tK3y1', 'aBcDeFgHiJk']); // in practice, use a secure store

function apiKeyMiddleware(req, res, next) {
  const key = req.get('X-API-Key');
  if (!key) {
    return res.status(401).json({ error: 'API key missing' });
  }
  if (!apiKeys.has(key)) {
    return res.status(403).json({ error: 'Invalid API key' });
  }
  // Ensure the key is not logged inadvertently
  req.apiKey = key;
  next();
}

Second, configure JWT validation with explicit algorithm and claim checks. Use a library like jsonwebtoken and enforce RS256 along with issuer and audience validation to prevent token confusion and replay.

const jwt = require('jsonwebtoken');
const fs = require('fs');
const publicKey = fs.readFileSync('public.key');

function jwtMiddleware(req, res, next) {
  const auth = req.get('Authorization');
  if (!auth || !auth.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Bearer token required' });
  }
  const token = auth.substring(7);
  try {
    const payload = jwt.verify(token, publicKey, {
      algorithms: ['RS256'],
      issuer: 'https://auth.example.com/',
      audience: 'https://api.example.com/',
  });
    req.user = payload;
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
}

Combine both middlewares when both factors are required, ensuring order reflects your security policy. For example, require API key first for route scoping, then validate JWT for user-level claims, and enforce scope reconciliation at the handler or via a dedicated authorization layer.

app.get('/v1/resources/:id', apiKeyMiddleware, jwtMiddleware, (req, res) => {
  // Example: ensure the resource owner matches the JWT subject and API key scope
  const { id } = req.params;
  if (!hasAccess(req.apiKey, req.user.sub, id)) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  res.json({ data: 'secure resource' });
});

Additionally, avoid accepting API keys in multiple formats (header, cookie, query) without normalization, and do not allow JWTs to implicitly grant broader permissions than intended. Scan configurations with middleBrick to detect specification mismatches, such as undefined security schemes or inconsistent key locations, and to verify that runtime behavior aligns with documented protections.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

What is a common JWT misconfiguration in Express APIs that increases risk when API keys are also used?
Accepting API keys via query parameters or cookies while JWTs use the Authorization header, and failing to strictly validate JWT algorithms and claims, can enable token swapping and bypasses.
How can Express APIs enforce separation between API keys and JWTs to reduce BOLA and misconfiguration risks?
Use distinct middlewares: validate API keys from a single header (e.g., X-API-Key) and verify JWTs with algorithm and claim checks; require both where appropriate and reconcile scopes at the handler level.