Signed but Not Verified: The JWT Validation Bugs That Let Attackers Forge Tokens

JSON Web Tokens are the default session format of the modern web. Signing one is a one-liner in every major library, and that ease is the problem: token-producing code is almost always better reviewed than the code that accepts it. Yet nearly every JWT-related breach you read about is not a broken signature algorithm. It is a verifier that failed to pin the algorithm, skipped a claim check, or trusted a header field that the attacker controls.

The pattern keeps repeating. Algorithm confusion vulnerabilities have existed since the earliest days of JWT libraries, and new CVEs with the same root cause — trusting the alg header in the token — still appear in mainstream web frameworks regularly. The signature math never failed. The verification code did.

This post walks through the verification bugs that actually get tokens forged: algorithm confusion, the none algorithm, missing expiry enforcement, weak HMAC secrets, and the revocation problem nobody plans for. All examples use golang-jwt v5, but the mistakes translate line for line to every language’s JWT ecosystem.

A Valid Signature Is Not an Authorization Decision

Start with what a valid signature actually proves: the payload was not modified after signing, and whoever signed it held the private key (or the shared secret). That is all. It does not prove that the token is meant for your API, that it has not expired, or that the roles inside it apply to the endpoint being called. Those are separate checks, and the JWT specification leaves most of them optional.

A verifier that only checks the signature accepts a token issued for a different service, a token signed last year, or a token minted for a test environment. The verifier should enforce every claim it depends on, server-side, every time. Here is a verify function that does, in Go:

package auth

import (
	"crypto/rsa"
	"errors"
	"fmt"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var rsaPublic *rsa.PublicKey

func verifyAccessToken(tokenString string) (jwt.MapClaims, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return rsaPublic, nil
	},
		jwt.WithValidMethods([]string{"RS256"}),
		jwt.WithIssuer("https://auth.example.com"),
		jwt.WithAudience("api://orders"),
		jwt.WithExpirationRequired(),
		jwt.WithLeeway(30*time.Second),
	)
	if err != nil {
		return nil, err
	}
	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok || !token.Valid {
		return nil, errors.New("invalid token claims")
	}
	return claims, nil
}

Every option in that call matters. WithValidMethods pins the algorithm whitelist before any key material is touched. The type assertion inside the key function is defense in depth: even if the parser option were accidentally dropped in a refactor, a token claiming any other algorithm is rejected before the key is returned. WithIssuer and WithAudience stop cross-service token reuse — a token minted for the billing API will not authenticate to the orders API. WithExpirationRequired closes the “token without an exp claim lives forever” hole. WithLeeway absorbs small clock skew between the machine that issued the token and the machine verifying it, so legitimate tokens are not rejected while still keeping the window tight.

Algorithm Confusion: Letting the Attacker Pick the Verifier

The JWT header is plain base64, decoded before the signature is checked, and every field in it is attacker-controlled. If your verification logic branches on the alg header, the attacker chooses which verification path runs. Two classics fall out of this mistake.

The first is the none algorithm. The JWA specification defines none for “unsecured” JWTs — tokens with no signature at all, intended for environments where integrity is guaranteed by transport. Some libraries historically accepted it by default, which means an attacker could strip the signature, set alg to none, and edit the payload freely. The tempting fix — blacklisting the string none — fails on case variants like NonE in implementations that compare loosely. Whitelisting the exact algorithms you expect is the only robust approach.

The second is RS256-to-HS256 key confusion. RS256 is asymmetric: the server publishes its public key — in a JWKS endpoint, a certificate, or anywhere public keys go. HS256 is symmetric: the same secret signs and verifies. If the verifier passes its configured key (the RSA public key) into whatever path the header requests, an attacker can take the public key, sign a forged token with it as the HMAC secret, and the signature matches — because HMAC does not care that the bytes happen to be an RSA key. The attacker only ever used public information. The vulnerable shape looks like this:

// DANGEROUS: the key is returned no matter which algorithm the header names.
// Illustrative snippet — do not deploy.
func verify(tokenString string) (*jwt.Token, error) {
	return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return rsaPublic, nil
	})
}

Current versions of golang-jwt refuse key types that do not match the claimed algorithm — an RSA key object is not a valid HMAC secret — and reject none unless a specific escape-hatch constant is passed as the key. But relying on a library’s internal type checks is half a defense, and the equivalent code in many other JWT libraries still happily HMAC-verifies with whatever bytes it is handed. Pin the algorithm explicitly with WithValidMethods, and assert the concrete signing method in the key function. Both checks together make the algorithm a server decision, not an attacker input.

Expiry: The Claim That Must Be Required

The exp claim is optional in the specification, and that optionality leaks into defaults. Plenty of libraries will accept a token with no exp at all — valid forever. Combined with a leaked signing key or an over-generous token lifetime, a verifier that does not require expiry is holding tokens that never die.

Enforcement starts at issuance. Set a short lifetime, and populate the registered claims your verifier will check:

package auth

import (
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func issueAccessToken(subject string) (string, error) {
	claims := jwt.RegisteredClaims{
		Subject:   subject,
		Issuer:    "https://auth.example.com",
		Audience:  jwt.ClaimStrings{"api://orders"},
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(15 * time.Minute)),
		IssuedAt:  jwt.NewNumericDate(time.Now()),
	}
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
	return token.SignedString(rsaPrivate)
}

Fifteen minutes is a common access-token lifetime: short enough that a stolen token expires before it is useful, long enough to avoid hammering your auth service. The classic objection to short lifetimes is clock skew, and WithLeeway answers it — but keep the leeway in seconds, not minutes; a generous leeway silently widens the effective expiry window for every token.

Weak Secrets and Untrusted Header Fields

HS256’s convenience hides a structural weakness: the same secret signs and verifies, so every service that can verify tokens can also mint them, and if that secret is guessable, everything is forgeable. Tools that brute-force HMAC secrets against a sample token are commodity software, and a weak or reused secret — anything derived from a codebase string, a project name, or a short passphrase — falls fast. If you use HMAC, generate the secret with a cryptographically secure random generator and treat its exposure as a total credential compromise. If verifiers are spread across services you do not fully control, prefer an asymmetric algorithm like RS256 or ES256, so verifiers hold only the public key and physically cannot mint tokens.

While hardening the header, remember that every header field is input. The kid (key ID) field tells the verifier which key to use, and naive implementations feed it straight into a database query or a file path to locate the key — an injection vector wearing a JWT costume. Look keys up through a fixed map or a parameterized query, and reject unknown key IDs.

You Cannot Log Out a JWT — Unless You Planned For It

Statelessness is sold as a JWT feature, and it is — until a user logs out, changes their password, or you discover a stolen token. A stateless verifier has no way to refuse a signature that is still cryptographically valid. Waiting for expiry is the only built-in revocation. A fifteen-minute access token bounds the damage without any revocation infrastructure at all.

For immediate revocation, pair short-lived access tokens with refresh tokens that are tracked server-side and rotated on use. Compromised sessions die with the refresh token; the stolen access token expires within one lifetime window. Where you need an immediate kill switch on access tokens themselves, maintain a denylist of revoked jti (token ID) values checked on each request — accepting that this re-introduces a storage lookup and a conscious trade against statelessness.

A Verification Checklist

  • Pin the algorithm server-side (WithValidMethods or your stack’s equivalent) and never derive it from the token header.
  • Reject none and every other unexpected algorithm by whitelist, never by blacklist.
  • Require exp, validate iss and aud on every request, and keep clock leeway to seconds.
  • Use an asymmetric algorithm when verifiers span services; if HMAC, use a 256-bit-plus random secret.
  • Pair short-lived access tokens with revocable, rotating refresh tokens.
  • Treat every header field, including kid, as attacker-controlled input.

None of these checks is exotic — token forging needs only one missed default. Pick a service you own, read its token verification path against the list. If you find a verifier that trusts the alg header or accepts tokens without expiry, you have found your next pull request.

Leave a Reply

Your email address will not be published. Required fields are marked *