HIGH missing tlsexpressbearer tokens

Missing Tls in Express with Bearer Tokens

Missing Tls in Express with Bearer Tokens — how this specific combination creates or exposes the vulnerability

When an Express API uses Bearer tokens over HTTP without Transport Layer Security (TLS), tokens are transmitted in cleartext. This specific combination exposes the token to network-level interception, undermining the security model of bearer-based authentication. TLS protects confidentiality and integrity in transit; without it, any intermediary on the network path can observe or modify unencrypted HTTP traffic.

Bearer tokens are often stored in Authorization headers (e.g., Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...). If the endpoint is served over HTTP, these tokens are sent as plaintext. Attackers on shared or compromised networks—such as public Wi‑Fi, corporate LANs with insufficient segmentation, or through compromised routers—can capture tokens using packet sniffing tools. Once captured, the token can be reused (token replay) to impersonate the victim user or service until it expires or is revoked. This maps to common attack patterns like credential theft and session hijacking, and it violates core principles of the OWASP API Security Top 10, particularly Broken Object Level Authorization (BOLA) and data exposure.

An unauthenticated scan by middleBrick can surface this risk under Data Exposure and Authentication checks when endpoints accept and process Bearer tokens over HTTP. Even if the token format appears valid, transmitting it without encryption exposes the API to trivial interception. The absence of TLS also weakens protections for other controls such as input validation and rate limiting, because intermediaries can alter requests in transit. For example, an attacker could modify a benign request to escalate privileges or redirect sensitive data if TLS is missing. middleBrick’s LLM/AI Security checks further highlight how missing TLS can amplify risks in AI-integrated endpoints, where token leakage might expose prompts or lead to unsafe consumption patterns.

Compliance frameworks such as PCI-DSS and GDPR require protection of authentication credentials in transit, and missing TLS is a direct non-compliance. In practice, developers sometimes assume internal networks are safe, but this assumption does not extend to all deployment environments—containers, serverless functions, and cloud load balancers may still expose HTTP endpoints inadvertently. Using TLS terminates this attack surface by encrypting the channel between client and server. When combined with Bearer tokens, TLS ensures tokens cannot be trivially harvested, enabling secure authentication and preserving the integrity of authorization decisions.

Bearer Tokens-Specific Remediation in Express — concrete code fixes

Remediation focuses on enforcing HTTPS and ensuring Bearer tokens are only accepted and transmitted over encrypted channels. In Express, you should terminate TLS at the load balancer or directly in the Node.js process using the https module. Never accept Bearer tokens over plain HTTP, and reject requests that do not use the correct scheme.

Example: enforcing HTTPS in Express with a simple middleware that rejects non-TLS requests.

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

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

// Middleware to enforce HTTPS in production-like checks (for illustration; enforce at load balancer as well)
app.use((req, res, next) => {
  if (process.env.NODE_ENV === 'production' && !req.secure) {
    return res.status(400).json({ error: 'HTTPS required' });
  }
  next();
});

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.slice(7);
  // Validate token via your auth provider
  res.json({ valid: true });
});

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

Example: validating Bearer tokens and ensuring secure transport with environment-aware enforcement.

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

// In production, reject non-secure requests; in development allow HTTP for convenience
if (process.env.NODE_ENV === 'production') {
  app.use((req, res, next) => {
    if (!req.secure) {
      return res.status(426).json({ error: 'Upgrade to TLS' });
    }
    next();
  });
}

function verifyBearer(req, res, next) {
  const auth = req.headers.authorization || '';
  const prefix = 'Bearer ';
  if (!auth.startsWith(prefix)) {
    return res.status(401).json({ error: 'Missing Bearer token' });
  }
  const token = auth.substring(prefix.length);
  if (!token) {
    return res.status(401).json({ error: 'Invalid Bearer token' });
  }
  // Replace with actual token introspection or validation
  req.user = { scope: 'read' }; // simplified example
  next();
}

app.get('/data', verifyBearer, (req, res) => {
  res.json({ message: 'Secure data', user: req.user });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

These examples illustrate how to integrate Bearer token validation with enforced transport security. In production, use a load balancer or reverse proxy (e.g., Nginx, AWS ALB) to handle TLS termination and forward traffic to Express over trusted internal networks. Avoid accepting Bearer tokens on HTTP routes, and apply middleware consistently across all protected endpoints. middleBrick’s CLI can be used to verify that endpoints reject tokens over HTTP and that TLS is correctly configured, while the GitHub Action can enforce security gates in CI/CD to prevent regressions.

Related CWEs: encryption

CWE IDNameSeverity
CWE-319Cleartext Transmission of Sensitive Information HIGH
CWE-295Improper Certificate Validation HIGH
CWE-326Inadequate Encryption Strength HIGH
CWE-327Use of a Broken or Risky Cryptographic Algorithm HIGH
CWE-328Use of Weak Hash HIGH
CWE-330Use of Insufficiently Random Values HIGH
CWE-338Use of Cryptographically Weak PRNG MEDIUM
CWE-693Protection Mechanism Failure MEDIUM
CWE-757Selection of Less-Secure Algorithm During Negotiation HIGH
CWE-261Weak Encoding for Password HIGH

Frequently Asked Questions

Can I safely accept Bearer tokens over HTTP in internal networks?
No. Even internal networks can be compromised or misconfigured. Always use TLS to protect tokens in transit; internal traffic can be intercepted via ARP spoofing, misconfigured VLANs, or compromised hosts. Enforce HTTPS consistently.
How does middleBrick detect missing TLS for Bearer token endpoints?
middleBrick scans unauthenticated endpoints and flags those that process Bearer tokens over HTTP under Data Exposure and Authentication checks. It also surfaces findings in the Data Exposure category and maps them to relevant compliance frameworks.