HIGH information disclosurebearer tokens

Information Disclosure with Bearer Tokens

How Information Disclosure Manifests in Bearer Tokens

Information disclosure in Bearer Tokens occurs when sensitive data is unintentionally exposed through token handling, logging, or transmission. Unlike opaque tokens, Bearer Tokens often contain claims that, if improperly managed, can leak critical information.

The most common manifestation is token logging in application logs. When developers log HTTP requests for debugging, the Authorization header containing the Bearer Token is often captured verbatim. This creates a persistent record of the token in log files, which may be accessible to unauthorized personnel or stored in less secure environments.

// Vulnerable: Logging entire request including Bearer Token
app.use((req, res, next) => {
  console.log(`Request: ${req.method} ${req.url} - Headers: ${JSON.stringify(req.headers)}`);
  next();
});

// Secure: Log only what's necessary
app.use((req, res, next) => {
  console.log(`Request: ${req.method} ${req.url} - Auth present: ${req.headers.authorization ? 'yes' : 'no'}`);
  next();
});

Another critical vector is token transmission over insecure channels. Bearer Tokens transmitted via HTTP instead of HTTPS are susceptible to interception through network sniffing or man-in-the-middle attacks. The token can then be used by attackers to impersonate legitimate users.

# Vulnerable: Token transmission over HTTP
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." http://api.example.com/endpoint

# Secure: Always use HTTPS
curl -H "Authorization: Bearer eyjhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." https://api.example.com/endpoint

Token leakage through referrer headers is another subtle but dangerous disclosure path. When API endpoints are accessed from web applications, the full URL containing the Bearer Token may be sent as a referrer to third-party sites, especially if the token is embedded in the URL rather than the Authorization header.

Client-side storage represents another significant risk. Storing Bearer Tokens in localStorage or sessionStorage exposes them to cross-site scripting (XSS) attacks. Once an attacker executes JavaScript on the page, they can retrieve all stored tokens and use them immediately.

// Vulnerable: Storing in localStorage
localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');

// Secure: Use httpOnly cookies instead
res.cookie('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', {
  httpOnly: true,
  secure: true,
  sameSite: 'strict'
});

Finally, overly verbose error messages can inadvertently disclose token structure or validation logic. Error responses that reveal whether a token is malformed, expired, or has insufficient scope provide attackers with valuable information for crafting targeted attacks.

// Vulnerable: Detailed error disclosure
if (!req.headers.authorization) {
  return res.status(401).json({ error: 'Missing Authorization header' });
}

// Secure: Generic error messages
if (!req.headers.authorization) {
  return res.status(401).json({ error: 'Authentication required' });
}

Bearer Tokens-Specific Detection

Detecting information disclosure in Bearer Tokens requires both automated scanning and manual code review. The middleBrick API security scanner excels at identifying these specific vulnerabilities through its comprehensive Bearer Tokens analysis.

middleBrick's Bearer Tokens scanner examines several critical areas automatically. It checks for tokens in HTTP response headers that should be excluded, such as server error pages or authentication failure responses. The scanner also analyzes whether tokens are transmitted over secure channels by attempting to access endpoints over HTTP and verifying HTTPS enforcement.

The scanner's log analysis capabilities detect when Bearer Tokens appear in application logs by searching for Authorization header patterns. It examines log files and HTTP response bodies for token exposure, flagging any instances where tokens are returned to clients or stored insecurely.

For client-side vulnerabilities, middleBrick simulates XSS attacks to determine if tokens stored in localStorage or sessionStorage can be accessed through injected scripts. It also checks for insecure token handling in client-side JavaScript by analyzing the application's frontend code for vulnerable patterns.

# Scan an API endpoint with middleBrick
middlebrick scan https://api.example.com/user/profile

# Scan with specific focus on authentication vulnerabilities
middlebrick scan https://api.example.com --category authentication

middleBrick's LLM security features add another layer of detection for AI-powered APIs that use Bearer Tokens. The scanner tests for system prompt leakage where tokens might be inadvertently included in AI model responses, and checks for excessive agency where tokens could be used by autonomous agents without proper authorization.

The scanner also verifies proper token validation and expiration handling. It tests whether expired tokens return appropriate error messages without revealing sensitive information about the token's structure or the system's validation logic.

Compliance mapping is built into middleBrick's detection engine. Information disclosure findings are automatically mapped to relevant standards including OWASP API Security Top 10 (A1: Broken Object Level Authorization, A2: Broken Authentication), PCI-DSS requirement 6.5.8, and SOC2 authentication controls.

middleBrick's continuous monitoring feature (Pro plan) regularly rescans APIs to detect new information disclosure vulnerabilities that may be introduced through code changes or configuration updates. This proactive approach ensures that token security remains intact throughout the development lifecycle.

Bearer Tokens-Specific Remediation

Remediating information disclosure vulnerabilities in Bearer Tokens requires a multi-layered approach focused on secure token handling, transmission, and storage. The following code examples demonstrate industry-standard practices for securing Bearer Tokens.

Secure token transmission is fundamental. Always enforce HTTPS and implement HSTS (HTTP Strict Transport Security) to prevent protocol downgrade attacks.

# Nginx configuration for secure Bearer Token transmission
server {
    listen 443 ssl http2;
    server_name api.example.com;
    
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    
    # Enforce HTTPS only
    if ($scheme != "https") {
        return 301 https://$server_name$request_uri;
    }
    
    # HSTS - Force HTTPS for 1 year
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

Proper token storage is critical for client-side applications. Avoid localStorage and sessionStorage entirely for Bearer Tokens. Instead, use secure, httpOnly cookies with appropriate security flags.

// Secure token storage on server
app.post('/login', async (req, res) => {
  const user = await authenticateUser(req.body);
  const token = generateJwt(user);
  
  res.cookie('authToken', token, {
    httpOnly: true,        // Prevent JS access
    secure: true,         // Only over HTTPS
    sameSite: 'strict',   // Prevent CSRF
    maxAge: 3600000       // 1 hour
  });
  
  res.json({ success: true });
});

// Secure middleware for protected routes
function authMiddleware(req, res, next) {
  const token = req.cookies.authToken;
  
  if (!token) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    // Generic error to prevent token structure disclosure
    return res.status(401).json({ error: 'Invalid token' });
  }
}

Secure logging practices prevent token exposure in application logs. Implement request sanitization middleware that removes or masks sensitive headers before logging.

// Request sanitization middleware
function sanitizeRequest(req, res, next) {
  // Create sanitized copy of headers
  const sanitizedHeaders = { ...req.headers };
  delete sanitizedHeaders.authorization;
  delete sanitizedHeaders.cookie;
  
  // Log only sanitized information
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - IP: ${req.ip}`);
  
  next();
}

// Express error handling with secure responses
app.use((err, req, res, next) => {
  console.error('Error:', err.message);
  
  // Never expose stack traces or token validation details
  res.status(500).json({ 
    error: 'An unexpected error occurred. Please try again later.' 
  });
});

Rate limiting and monitoring help detect and prevent token abuse. Implement rate limiting on authentication endpoints and monitor for unusual token usage patterns.

const rateLimit = require('express-rate-limit');

// Rate limit authentication attempts
const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // limit each IP to 5 requests per windowMs
  message: 'Too many authentication attempts'
});

app.use('/api/auth', authLimiter);

// Monitor token usage patterns
const jwtMonitor = require('jwt-monitor');

jwtMonitor.on('token-used', (tokenData) => {
  if (tokenData.issuedAt < Date.now() - 24 * 60 * 60 * 1000) {
    console.warn('Token used after 24 hours:', tokenData);
  }
});

Frequently Asked Questions

How can I tell if my Bearer Tokens are being logged insecurely?
Search your application code and configuration files for patterns like console.log, logger.info, or similar logging statements that include req.headers or req.headers.authorization. Also check your log files for any occurrences of "Authorization: Bearer" or JWT patterns. middleBrick's scanner automatically detects token logging by analyzing your application's runtime behavior and log output.
Should I store Bearer Tokens in localStorage for my single-page application?
No, localStorage is vulnerable to XSS attacks where malicious scripts can read stored tokens. Instead, use httpOnly cookies sent over HTTPS, or implement a refresh token pattern where short-lived access tokens are stored in memory while refresh tokens are kept in secure httpOnly cookies. middleBrick's scanner specifically checks for localStorage token storage and flags it as a high-risk vulnerability.