HIGH broken authenticationjwt tokens

Broken Authentication with Jwt Tokens

How Broken Authentication Manifests in Jwt Tokens

Broken authentication in JSON Web Tokens (JWT) typically arises from weak token validation, insecure signing algorithms, or mishandled token lifecycle. Attack paths include accepting unsigned tokens (alg: none), using weak secrets for HMAC, or failing to verify the audience (aud) and issuer (iss) claims. These issues can lead to identity impersonation, privilege escalation, and unauthorized access to protected resources.

Specific JWT code paths where broken authentication appears include token parsing endpoints, refresh-token handlers, and callback routes that exchange codes for tokens. For example, a Node.js endpoint that decodes without verification can be tricked into trusting attacker-supplied tokens:

const jwt = require('jsonwebtoken');
const token = req.headers.authorization?.split(' ')[1];
// Vulnerable: no verification, trusting the token payload
const payload = jwt.decode(token);

Another common pattern is accepting tokens signed with the none algorithm, which bypasses signature checks entirely. If a server does not explicitly enforce a signing method, an attacker can forge a token with an empty signature and gain unauthorized access. Additionally, missing checks for token expiration (exp) and not-before (nbf) can enable replay attacks or use of stale tokens.

Server-side session management that stores sensitive data in JWT payloads without encryption can also contribute to broken authentication, especially if tokens are transmitted over non-HTTPS channels or stored insecurely on the client. Misconfigured token revocation mechanisms, such as not checking a denylist or rotating signing keys, further exacerbate the risk. These JWT-specific vectors are well aligned with OWASP API Top 10 authentication and session management failures, and they underscore the need for strict validation at every integration point.

Jwt Tokens-Specific Detection

Detecting broken authentication in JWT tokens requires validating the token structure, signature, claims, and transport security. Effective checks include verifying the algorithm is explicitly set (e.g., RS256 or ES256), ensuring the token is signed and not unsigned (alg: none), and confirming that standard claims such as iss, aud, exp, and nbf are present and valid. Failing to enforce these checks can allow attackers to substitute identities or escalate privileges.

middleBrick scans for these issues by running unauthenticated checks against the API surface. During a scan, it submits requests that probe JWT handling paths, such as endpoints that accept tokens in headers or cookies, and analyzes responses for signs of weak validation. For example, it tests whether the API accepts tokens signed with the none algorithm and whether it properly rejects tokens with invalid signatures or missing claims. The scanner also inspects related OpenAPI/Swagger specs (2.0, 3.0, 3.1) with full $ref resolution to map declared security schemes to runtime behavior, cross-referencing spec definitions with observed findings.

Additionally, middleBrick evaluates token transmission practices, such as whether tokens appear in URLs or logs, and checks for excessive agency patterns in any integrated LLM endpoints that might expose or misuse JWTs. Findings include severity levels and remediation guidance, helping teams prioritize fixes based on exploitability and impact. By combining runtime tests with spec analysis, the scanner provides a comprehensive view of JWT authentication weaknesses without requiring credentials or agents.

Jwt Tokens-Specific Remediation

Remediating broken authentication for JWT tokens involves enforcing strict validation, using strong signing algorithms, and applying secure token lifecycle practices. Always verify the token signature and explicitly specify the allowed algorithm; never rely on the token header to dictate the algorithm. For HMAC, use a strong, rotated secret; for asymmetric cryptography, use RS256 or ES256 with properly managed private keys and certificates.

Validate standard claims such as iss, aud, exp, nbf, and jti. Enforce HTTPS for all token transmission and avoid storing sensitive data in the token payload unless it is encrypted. Implement short expiration times and use refresh tokens with strict rotation and revocation checks. Below are concrete code examples that demonstrate secure JWT handling in common environments.

Node.js with jsonwebtoken, enforcing algorithm and claims verification:

const jwt = require('jsonwebtoken');
const publicKey = '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----';
const token = req.headers.authorization?.split(' ')[1];
try {
  const payload = jwt.verify(token, publicKey, {
    algorithms: ['RS256'],
    issuer: 'https://auth.example.com',
    audience: 'https://api.example.com',
  });
  req.user = payload;
} catch (err) {
  res.status(401).json({ error: 'invalid_token' });
}

Go with go-jwt, validating claims and algorithm:

import (
  "github.com/golang-jwt/jwt/v5"
)
func validateToken(raw string) (jwt.Claims, error) {
  keyFunc := func(token *jwt.Token) (interface{}, error) {
    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
      return nil, fmt.Errorf("unexpected algorithm: %v", token.Header["alg"])
    }
    return []byte(os.Getenv("JWT_SECRET")), nil
  }
  return jwt.Parse(raw, keyFunc, jwt.WithValidators(jwt.ValidateIssuer("https://auth.example.com"), jwt.WithAudience("https://api.example.com")))
}

These examples emphasize explicit algorithm selection, issuer and audience validation, and proper error handling. Complementary measures include monitoring token usage, rotating keys, and integrating token revocation checks where applicable. By addressing JWT-specific risks systematically, teams can significantly reduce authentication bypass and identity compromise.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

Does middleBrick test for JWT algorithm confusion attacks?
Yes. The scanner checks whether the API accepts tokens signed with the none algorithm and verifies that the server enforces a specific signing method.
Can JWT-related findings be integrated into CI/CD pipelines?
Yes. With the middleBrick Pro plan, findings can be enforced in CI/CD pipelines via the GitHub Action, which can fail builds if security scores drop below your defined threshold.