HIGH integrity failuresexpressbearer tokens

Integrity Failures in Express with Bearer Tokens

Integrity Failures in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability

An integrity failure in an Express API that uses Bearer Tokens occurs when the application accepts a token but does not adequately verify its authenticity, integrity, or scope before using it to make authorization decisions. This specific combination is common because Bearer Tokens are easy to transmit via the Authorization header, yet they are only as trustworthy as the mechanisms that validate them.

Without proper validation, an attacker can supply a malformed, tampered, or algorithm-swapped token (e.g., an unsigned token or a token signed with a different key) and the server may treat it as valid. This breaks integrity because the server should reject tokens it cannot verify. In Express, this often happens when developers skip verifying signatures, skip checking the expected issuer (iss) or audience (aud), or fail to enforce token binding to a specific scope or session context. These gaps allow an attacker to escalate privileges or access resources that should be restricted.

Another integrity risk arises from how Express middleware processes the token. If the application places the token value into logs, error messages, or downstream HTTP calls without validating it, it can expose sensitive material or enable SSRF or injection attacks. Additionally, if the token is used to derive access decisions without rechecking permissions on each request (authorization coupling), stale or elevated tokens can be reused to perform actions outside the original intent, violating integrity.

Real-world attack patterns mirror this: consider a compromised or forged token being accepted due to an absent issuer check, leading to unauthorized access to admin endpoints. This aligns with common weaknesses in API security and is a key focus of checks such as BOLA/IDOR and Authentication in middleBrick scans, which test whether endpoints incorrectly trust unverified tokens. These scans also flag missing integrity checks in token handling as a high-severity finding because they can lead to unauthorized access and data exposure.

To detect such issues, scanners analyze the OpenAPI specification for missing security scheme definitions and inconsistencies between declared authentication and runtime behavior. They also perform active tests, such as sending malformed Bearer Tokens to endpoints and observing whether the server incorrectly accepts them. This helps identify integrity failures before attackers can exploit them in production.

Bearer Tokens-Specific Remediation in Express — concrete code fixes

Remediation focuses on strict validation of Bearer Tokens in Express before using them for authorization. Always verify the token signature, validate standard claims, and enforce scope and session checks. Below are concrete, working examples.

1. Validate JWT Bearer Tokens with a library

Use a well-maintained library like jsonwebtoken to verify signatures and claims. Do not manually parse the token payload for security decisions.

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----`;

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, PUBLIC_KEY, { algorithms: ['RS256'], issuer: 'https://auth.example.com', audience: 'api.example.com' }, (err, decoded) => {
    if (err) return res.sendStatus(403);
    req.user = decoded;
    next();
  });
}

app.get('/admin', authenticateToken, (req, res) => {
  res.json({ message: 'Admin access granted', user: req.user.sub });
});

app.listen(3000, () => console.log('Server running on port 3000'));

2. Enforce scope and custom claims

After verifying the token, check scope or custom claims to ensure the token is authorized for the requested action. This prevents privilege escalation via token reuse.

function requireScope(requiredScope) {
  return (req, res, next) => {
    const tokenScopes = req.user.scope || '';
    const scopes = tokenScopes.split(' ');
    if (!scopes.includes(requiredScope)) {
      return res.status(403).json({ error: 'insufficient_scope' });
    }
    next();
  };
}

app.get('/write', authenticateToken, requireScope('write:data'), (req, res) => {
  res.json({ message: 'Write operation allowed' });
});

3. Avoid logging or forwarding raw tokens

Ensure tokens are not inadvertently exposed in logs or forwarded to downstream services. Sanitize headers before logging.

app.use((req, res, next) => {
  const sanitizedHeaders = { ...req.headers };
  if (sanitizedHeaders.authorization) {
    sanitizedHeaders.authorization = '[secure]';
  }
  // Use sanitizedHeaders for logging or monitoring
  next();
});

4. Use HTTPS and short token lifetimes

Always serve your API over HTTPS to prevent token interception. Configure short expiration times for Bearer Tokens and use refresh tokens with strict validation to limit the impact of token leakage.

These steps reduce the risk of integrity failures by ensuring that only valid, scoped, and properly verified Bearer Tokens are accepted. They align with findings reports from tools like middleBrick, which highlight missing issuer/audience checks and improper token validation as high-severity issues.

Frequently Asked Questions

How can I test if my Express endpoint incorrectly accepts malformed Bearer Tokens?
Do I need to include Bearer Token validation in my OpenAPI spec for middleBrick to flag integrity issues?