HIGH Authentication

Token Leakage in APIs

What is Token Leakage?

Token leakage occurs when authentication tokens, API keys, or session identifiers are inadvertently exposed in API responses, logs, error messages, or client-side code. These tokens serve as credentials that prove a user's identity or authorization to access protected resources. When tokens leak, attackers can harvest them and use them to impersonate legitimate users, escalate privileges, or access sensitive data without proper authentication.

The vulnerability typically manifests when APIs return tokens in response bodies, headers, or URLs even when they shouldn't be exposed. Common scenarios include debug endpoints that reveal authentication tokens, error messages that include stack traces with tokens, or client-side JavaScript that logs tokens to the browser console. Unlike broken authentication where tokens are stolen through interception, token leakage involves tokens being willingly sent to the wrong party.

How Token Leakage Affects APIs

Token leakage creates multiple attack vectors that can compromise API security. An attacker who discovers a leaked token can immediately use it to authenticate as the victim user, gaining full access to their account and associated data. This enables account takeover attacks where the attacker can change passwords, modify personal information, or perform actions on behalf of the user.

In more sophisticated attacks, leaked refresh tokens can be exchanged for new access tokens, allowing persistent access even if the original token expires. Attackers can also chain token leakage with other vulnerabilities—for example, using a leaked admin token to exploit IDOR (Insecure Direct Object Reference) vulnerabilities and access other users' data. The impact extends beyond individual accounts when tokens grant elevated privileges, potentially exposing entire systems or sensitive organizational data.

Consider a scenario where an API returns JWT tokens in response headers even for failed authentication attempts. An attacker can automate requests to the login endpoint, collect valid tokens from error responses, and immediately use them to access the system. This transforms a simple enumeration attack into a full account takeover with minimal effort.

How to Detect Token Leakage

Detecting token leakage requires systematic testing of API responses across all endpoints and HTTP methods. Security teams should examine every response for unexpected tokens, paying special attention to error messages, validation failures, and debug endpoints. Tools like middleBrick automate this detection by scanning API responses for authentication tokens, session identifiers, and other sensitive credentials that appear where they shouldn't.

middleBrick's token leakage detection specifically looks for JWT tokens, OAuth access tokens, session cookies, and API keys in response bodies, headers, and URLs. The scanner tests both successful and failed requests, as many APIs inadvertently expose tokens in error conditions. For example, a 401 Unauthorized response might still include a valid refresh token in its headers, or a validation error might return a JWT in the response body.

Manual testing should include examining responses for patterns like:

  • Authorization: Bearer token headers in unexpected responses
  • access_token, refresh_token, or id_token fields in JSON responses
  • Set-Cookie headers with session identifiers
  • Authorization headers in error responses
  • Debug information containing authentication headers

middleBrick's black-box scanning approach tests the unauthenticated attack surface, identifying tokens that are exposed without requiring any credentials. This reveals vulnerabilities that would be visible to any attacker probing the API.

Prevention & Remediation

Preventing token leakage requires strict control over where and when tokens are included in API responses. The fundamental principle is to only return tokens when explicitly requested and necessary for the client's operation. Authentication endpoints should return tokens only in successful authentication responses, and all other endpoints should never include authentication tokens in their responses.

Here's a code example showing proper token handling:

// INSECURE - token leakage in error responses
app.post('/login', (req, res) => {
  const token = generateToken(user);
  if (authenticate(user, req.body.password)) {
    res.json({ token, user: user.id });
  } else {
    res.status(401).json({ 
      error: 'Invalid credentials', 
      token: token // LEAKED - should not return token on failure
    });
  }
});

// SECURE - proper token handling
app.post('/login', (req, res) => {
  if (!authenticate(user, req.body.password)) {
    return res.status(401).json({ 
      error: 'Invalid credentials' 
    });
  }
  
  const token = generateToken(user);
  res.json({ token, user: user.id });
});

Additional preventive measures include:

  • Implementing comprehensive logging that redacts tokens before writing to logs
  • Using HTTP-only cookies for session management instead of exposing tokens in JavaScript
  • Validating that tokens are only returned from authentication endpoints
  • Implementing response filtering to strip sensitive headers from error responses
  • Using Content Security Policy headers to prevent token exfiltration via XSS

For APIs using JWT tokens, consider implementing token rotation and short expiration times to minimize the impact of any potential leakage. Always use HTTPS to prevent token interception during transit, though this doesn't address leakage in responses themselves.

Real-World Impact

Token leakage has been implicated in several high-profile security incidents. In 2021, a major e-commerce platform suffered a data breach when authentication tokens were inadvertently included in error responses from their API. Attackers used automated scripts to collect valid tokens from failed login attempts, leading to account takeovers affecting millions of users.

The vulnerability CVE-2020-9283 in a popular authentication library demonstrated how tokens could leak through error handling. When authentication failed, the library returned detailed error messages including the original authentication token in the response body. This allowed attackers to enumerate valid tokens and bypass authentication entirely.

Financial services APIs are particularly vulnerable to token leakage because they often handle high-value transactions. A leaked OAuth token could grant attackers access to banking APIs, enabling unauthorized transfers or account modifications. Healthcare APIs face similar risks, where leaked tokens could expose protected health information (PHI) in violation of HIPAA regulations.

middleBrick's scanning methodology helps organizations identify these vulnerabilities before attackers do. By testing the unauthenticated attack surface and examining all response types, middleBrick can detect token leakage that traditional penetration testing might miss. The scanner's 12 security checks include specific analysis for authentication-related vulnerabilities, ensuring comprehensive coverage of token handling across your entire API surface.

Frequently Asked Questions

What's the difference between token leakage and broken authentication?
Token leakage involves tokens being exposed in API responses where they shouldn't appear, while broken authentication refers to weaknesses in the token validation or generation process. Token leakage is about exposure location, whereas broken authentication is about token security. Both can lead to account takeover, but token leakage specifically means tokens are being sent to unintended recipients.
Can token leakage be detected automatically?
Yes, automated tools like middleBrick can detect token leakage by scanning API responses for authentication tokens, session identifiers, and other credentials that appear in unexpected locations. middleBrick's black-box scanning tests all endpoints and response types without requiring credentials, identifying tokens exposed in error messages, debug responses, or other unintended locations.
Are refresh tokens more dangerous when leaked than access tokens?
Yes, refresh tokens are typically more dangerous when leaked because they have longer lifespans and can be exchanged for new access tokens. While access tokens often expire in minutes or hours, refresh tokens can remain valid for days or weeks. A leaked refresh token can provide persistent access to an account even if the original access token is revoked or expires.