HIGH token leakageexpressbearer tokens

Token Leakage in Express with Bearer Tokens

Token Leakage in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Token leakage in Express applications using Bearer tokens occurs when sensitive authentication tokens are exposed beyond their intended scope, typically through logging, error messages, or insecure transport and storage practices. Because Bearer tokens are sent in the Authorization header as Authorization: Bearer <token>, any mishandling at the HTTP layer, in application code, or via tooling can inadvertently expose these credentials.

Express apps often leak Bearer tokens via verbose error traces that include request headers, insecure HTTP instead of HTTPS, or logs that record full headers for debugging. For example, a common development practice of logging req.headers can expose Authorization values in console output or log files, making tokens accessible to anyone with access to those logs. Similarly, misconfigured CORS or improperly set security headers can allow client-side scripts or unintended origins to observe token-bearing requests. In a black-box scan, such leakage is detectable through checks for sensitive data exposure and insecure transport, where the scanner tests whether tokens can be observed in responses, logs, or through error handling paths.

Middleware that processes authentication is a frequent vector. If an Express route reads req.headers.authorization and passes it to downstream services, logging, or error handlers without redaction, the token may be written to logs or reflected in API responses. A real-world pattern involves sending the full Authorization header to a logging service or including it in URLs during redirects, which can be captured in browser history or server access logs. Another scenario is using Bearer tokens for session-like behavior without enforcing short lifetimes or token binding, increasing the window for exposure if logs are compromised. Because these checks run unauthenticated and in parallel, the scanner evaluates whether Authorization headers are present in responses, whether HTTPS is enforced, and whether token values appear in any observable output, aligning with checks for Data Exposure and Input Validation.

The interplay of Express routing, header handling, and Bearer token usage means leakage can occur at multiple layers: transport (missing or weak encryption), application (logging and error handling), and client-side (storage and transmission by browsers or mobile clients). The scanner validates that HTTPS is used, that sensitive headers are not echoed in responses, and that error messages do not include Authorization values. Findings may reference issues such as inadvertent header reflection or missing transport protections, which map to OWASP API Top 10 and common misconfigurations around credential exposure.

Bearer Tokens-Specific Remediation in Express — concrete code fixes

Remediation focuses on preventing the inclusion of Bearer tokens in logs, error messages, and non-HTTPS traffic, and on ensuring tokens are handled with minimal exposure. Below are concrete Express patterns that reduce leakage risk.

1. Avoid logging Authorization headers

Never log the full request object or headers that include Authorization. Redact sensitive keys before logging.

// Insecure: logs full headers, exposing Bearer tokens
app.use((req, res, next) => {
  console.log('Incoming headers:', req.headers);
  next();
});

// Secure: redact Authorization before logging
app.use((req, res, next) => {
  const safeHeaders = { ...req.headers };
  if (safeHeaders['authorization']) {
    safeHeaders['authorization'] = '[redacted]';
  }
  console.log('Incoming headers:', safeHeaders);
  next();
});

2. Enforce HTTPS and secure transport

Always use HTTPS in production to protect tokens in transit. In development, use tools like mkcert; in Express, enforce redirects or reject HTTP.

// Redirect HTTP to HTTPS in production
const http = require('http');
const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();

// HTTPS server with proper certs
const httpsServer = https.createServer({
  key: fs.readFileSync('/path/to/privkey.pem'),
  cert: fs.readFileSync('/path/to/fullchain.pem')
}, app);

// Optional: redirect HTTP to HTTPS
http.createServer((req, res) => {
  res.writeHead(301, { 'Location': 'https://' + req.headers.host + req.url });
  res.end();
}).listen(80);

app.get('/secure', (req, res) => {
  res.json({ ok: true });
});

httpsServer.listen(443);

3. Centralized auth middleware with redaction on error

Create an authentication middleware that validates Bearer tokens and ensures errors do not reflect token values.

function authenticate(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  // Verify token with your auth provider (e.g., JWT verification)
  try {
    // verifyToken is a placeholder for your verification logic
    const payload = verifyToken(token);
    req.user = payload;
    next();
  } catch (err) {
    // Do not include token or raw error details in response
    console.error('Auth error:', err.message);
    res.status(401).json({ error: 'Invalid token' });
  }
}

app.use(authenticate);

app.get('/profile', (req, res) => {
  res.json({ user: req.user });
});

4. Secure cookie attributes if storing tokens client-side

If using cookies to store tokens (e.g., for browser-based clients), set Secure, HttpOnly, and SameSite attributes appropriately.

res.cookie('token', tokenValue, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
  maxAge: 3600000
});

5. Validate and sanitize inputs to prevent token reflection

Ensure that user-controlled data does not inadvertently include or echo Authorization headers.

app.post('/webhook', express.json(), (req, res) => {
  const data = req.body;
  // Never include raw Authorization headers in responses or logs
  if (data && data.action) {
    // Process data safely
    res.json({ received: true });
  } else {
    res.status(400).json({ error: 'Bad request' });
  }
});

By combining transport security, careful logging, and robust middleware, Express applications can significantly reduce the risk of Bearer token leakage while maintaining clear, secure authentication flows.

Frequently Asked Questions

Can a Bearer token be safely logged if it is redacted in production logs?
Avoid logging Bearer tokens entirely; even redacted logs can create confusion and risk if handling is inconsistent. Use structured logging that excludes Authorization headers by design.
Does using HTTPS alone prevent all token leakage in Express?
HTTPS protects tokens in transit, but tokens can still be leaked via logs, error messages, client-side storage, or insecure redirects. Apply transport security alongside secure coding and logging practices.