HIGH man in the middleexpressbearer tokens

Man In The Middle in Express with Bearer Tokens

Man In The Middle in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability

A Man In The Middle (MitM) attack against an Express API that uses Bearer Tokens occurs when an attacker can intercept or alter traffic between the client and the server. Because Bearer Tokens are typically transmitted in HTTP headers (e.g., Authorization: Bearer ), unencrypted or improperly secured channels create a high-risk scenario. If an Express app serves endpoints over HTTP or accepts tokens on both HTTP and HTTPS without enforcing strict transport security, an attacker on the same network can capture or tamper with requests, leading to token theft and unauthorized access.

In Express, common misconfigurations that enable MitM include missing HTTP Strict Transport Security (HSTS) headers, lack of secure cookie attributes, and not redirecting HTTP to HTTPS. For example, an Express route that reads Authorization headers without validating the protocol can inadvertently expose tokens in cleartext:

app.get('/profile', (req, res) => {
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  const token = auth.split(' ')[1];
  // Use token, e.g., verify with a JWT library
  res.json({ message: 'Profile data' });
});

If this endpoint is reachable over HTTP, an attacker can intercept the token and reuse it (token replay). Even with HTTPS, missing or weak certificate validation on the client side can enable MitM via malicious proxies or self-signed certificates. Compounded risks include insecure storage on the client, where tokens may be accessible to scripts if cookies or localStorage are used without the Secure and HttpOnly flags. The combination of Express routing that does not enforce secure transport and Bearer Tokens transmitted in clear text significantly increases the likelihood of successful interception and abuse.

Additionally, improper CORS configurations in Express can expose tokens to unauthorized origins, enabling MitM via malicious web applications that trick users’ browsers into sending authenticated requests. Attack patterns such as DNS spoofing, ARP poisoning, or compromised Wi-Fi access points further illustrate how network-level weaknesses can undermine token-based authentication in Express, making robust transport and header security essential.

Bearer Tokens-Specific Remediation in Express — concrete code fixes

Remediation focuses on enforcing HTTPS, protecting token transmission, and hardening Express configurations to prevent interception. Always redirect HTTP to HTTPS and set HSTS headers to instruct browsers to use secure connections only:

const https = require('https');
const http = require('http');
const fs = require('fs');
const express = require('express');
const app = express();

// Redirect HTTP to HTTPS
http.createServer(app).listen(80, () => {
  console.log('HTTP server redirecting to HTTPS');
});

const httpsOptions = {
  key: fs.readFileSync('path/to/private.key'),
  cert: fs.readFileSync('path/to/certificate.crt'),
};

https.createServer(httpsOptions, app).listen(443, () => {
  console.log('HTTPS server running on port 443');
});

// HSTS header for HTTPS responses
app.use((req, res, next) => {
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  next();
});

Ensure Bearer Tokens are transmitted only over HTTPS and avoid logging or exposing them in error messages. Validate and verify tokens using a reliable library, and scope checks to the required routes:

const jwt = require('jsonwebtoken');

const authenticateBearer = (req, res, next) =>
{
  const auth = req.headers.authorization;
  if (!auth || !auth.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  const token = auth.split(' ')[1];
  try {
    const decoded = jwt.verify(token, process.env.JWT_PUBLIC_KEY);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid token' });
  }
};

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

Apply secure cookie attributes if storing tokens in cookies, and configure CORS to allow only trusted origins. Use the cors middleware explicitly instead of broad patterns:

const cors = require('cors');

const corsOptions = {
  origin: 'https://trusted.example.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Authorization', 'Content-Type'],
  credentials: true,
};

app.use(cors(corsOptions));

For additional assurance, rotate tokens regularly and prefer short-lived access tokens with refresh token mechanisms stored with HttpOnly and Secure flags. The combination of enforced HTTPS, strict transport headers, precise CORS rules, and proper token validation significantly reduces the attack surface for MitM against Express APIs using Bearer Tokens.

Frequently Asked Questions

Can middleBrick detect an Express API vulnerable to MitM with Bearer Tokens?
Yes. middleBrick scans unauthenticated attack surfaces and includes checks such as Data Exposure and Encryption, which identify missing transport protections and token exposure risks in Express endpoints.
Does the middleBrick CLI help enforce secure Bearer Token handling in Express?
Yes. Use the CLI tool with middlebrick scan to retrieve structured findings and remediation guidance, including HTTPS enforcement and header security recommendations for Express.