Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A code review finds a hand-written JWT filter that decodes the token, reads the alg header and chooses the verification method from it. What attacks does this allow, and what should the code do?

A filter that reads the alg header and picks the verification method from it lets the attacker choose how their own token is checked. That opens two classic attacks: alg "none", where an unsigned token is accepted, and algorithm confusion, where the RSA public key is used as an HMAC secret so the attacker can sign tokens. The fix is to fix the expected algorithm and keys in configuration, use a maintained decoder such as Spring Security's NimbusJwtDecoder, and validate iss, aud and exp as well.

Why this question is asked

Hand-written JWT filters appear in many older Spring services, usually written before the team knew about Spring Security's resource server support. They tend to work in every happy-path test, which is exactly why the flaws survive for years. Interviewers like this question because it checks whether we understand what a signature actually proves and who gets to decide how it is checked. In this answer, we will recap how a JWT is built, reproduce the flawed filter, walk through the two attacks it allows, and then replace it with a configured decoder that also checks the claims hand-written code tends to forget.

1A Quick Recap of How a JWT Is Signed

A JWT (JSON Web Token) is three Base64url-encoded parts joined by dots: a header, a payload of claims, and a signature. The header says which algorithm produced the signature, for example {"alg":"RS256","kid":"key-7"}. The payload holds claims such as sub (the user), iss (the issuer that created the token), aud (the audience, meaning the service the token is meant for) and exp (the expiry time).

The signature is computed over the first two parts. With RS256 the identity provider signs with its RSA private key and everyone verifies with the matching public key, which is published openly. With HS256 the same shared secret is used both to sign and to verify, so anyone who knows the secret can create tokens.

The important point is that the header is just data inside the token. The attacker writes it. Nothing about the header is trustworthy until the signature has been verified with a method we chose ourselves.

2Reproducing the Flawed Filter

Here is a simplified version of the kind of code a review might find. It decodes the header, reads alg, and dispatches on it.

Java
String[] parts = token.split("\\.");
JsonNode header = mapper.readTree(Base64.getUrlDecoder().decode(parts[0]));
String alg = header.get("alg").asText(); // chosen by whoever built the token
boolean valid = switch (alg) {
case "RS256" -> rsaVerify(parts, rsaPublicKey); // the intended path
case "HS256" -> hmacVerify(parts, rsaPublicKeyPemBytes); // "for the legacy client"
case "none" -> true; // "for local testing"
default -> false;
};
if (valid) { setAuthentication(readClaims(parts[1])); } // no iss, aud or exp checks

Notice that the token decides which branch runs. Every branch that exists for convenience is now a branch the attacker can select. Notice also that, once the signature passes, the claims are trusted as they are: an expired token, or a token issued for a different service, still logs the user in.

3Attack 1: The alg none Token

The JWT specification defines "none" for unsecured tokens, which carry an empty signature. If the code honours that value, an attacker needs no key at all. They write a header of {"alg":"none"}, a payload with sub set to an administrator and exp far in the future, and leave the third part empty. The switch returns true and the filter authenticates them.

This sounds too obvious to happen, but it has appeared in real libraries and in code like the example above, often because a developer added the branch to make local testing easier and it was never removed. Some variants use "None" or "NONE" to get past a naive string comparison, which is another reason not to dispatch on the header at all.

4Attack 2: Algorithm Confusion

The second attack is subtler. The service verifies RS256 tokens with an RSA public key, and that public key is public: it is on the identity provider's JWKS endpoint for anyone to download. The attacker builds a token with alg set to HS256 and computes an HMAC over it, using the bytes of that public key as the HMAC secret.

The flawed filter sees HS256 and verifies the HMAC with the same public key bytes. The two computations match, so the forged token is accepted. The attacker has turned a key that was only meant to verify into a key that can sign. The reason this works is that the code lets one key be used with two different algorithms, chosen by the token.

Step throughAlgorithm confusion against the flawed filter
AttackerJWKS endpointFlawed filter
GET public key
RSA public key (public data)
Build token, alg = HS256
HMAC-sign it with the public key bytes
Send forged token
Read alg = HS256 from header
HMAC-verify with the same public key bytes
200 OK as the forged user

8 messages in order. Play them, or step through them one at a time.

The attacker never needs the private key, because the filter lets the token pick the algorithm.

5What the Code Should Do Instead

The verifier must decide the algorithm and keys from its own configuration, never from the token. In Spring Security this is what the OAuth2 resource server and NimbusJwtDecoder already do: the decoder is built with a JWK Set URI and an allowed algorithm, and tokens whose header names any other algorithm are rejected before any key is used.

Java
@Bean
JwtDecoder jwtDecoder(@Value("${auth.issuer}") String issuer) {
NimbusJwtDecoder decoder = NimbusJwtDecoder
.withJwkSetUri(issuer + "/.well-known/jwks.json")
.jwsAlgorithm(SignatureAlgorithm.RS256) // the only algorithm we accept
.build();
OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(
JwtClaimNames.AUD, aud -> aud != null && aud.contains("orders-api"));
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
JwtValidators.createDefaultWithIssuer(issuer), // exp, nbf and iss
audience)); // aud
return decoder;
}
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
return http.build();
}
// token with alg none -> 401
// token with alg HS256 -> 401
// expired RS256 token -> 401
// RS256 token, aud = billing-api -> 401

What changed is who makes the decision. The algorithm list is fixed, the keys come from the issuer's JWKS and are selected by kid, and an unexpected alg is simply a failure. The hand-written switch and its convenience branches disappear, and with them the custom Base64 and JSON parsing, which had its own chances to go wrong.

Spring Boot can also build this from properties: spring.security.oauth2.resourceserver.jwt.issuer-uri, jws-algorithms and audiences. The default validators check exp and nbf with a small clock skew, and the issuer validator checks iss. The audience check matters as much as the signature: without it, a perfectly valid token issued for another service in the same company would be accepted here. Check your Spring Boot version for the exact property names.

Finally, the review should ask for tests that try to break the filter: a none token, an HS256 token signed with the public key, an expired token and a token for another audience, each expected to get 401. Those four tests would have caught every flaw in the original code.

6Follow-up questions

Is it enough to just delete the none branch?

No. Deleting it fixes the first attack but leaves algorithm confusion and the missing claim checks. The underlying problem is that the token chooses the verification path. Once the algorithm and key are fixed in configuration, both attacks fail for the same reason, and the code becomes much smaller.

Why not keep the hand-written filter but harden it?

Because signature checking is full of small traps: header parsing, key selection by kid, constant-time comparison, clock skew, key rotation and caching. A maintained library such as Nimbus, wrapped by Spring Security, has already handled these and receives security fixes. Our own code would need the same care forever, and nobody gets reviewed on it until it fails.

What if we really have a legacy client that uses HS256?

Then give that client its own decoder with its own secret, ideally on a separate endpoint or filter chain, and never share a key between algorithms. Better still, plan to move the client onto tokens signed by the identity provider so only asymmetric keys remain.

7Conclusion

In this answer, we saw that a filter which reads alg from the token lets an attacker choose how the token is verified. That allows unsigned tokens through alg none and forged tokens through algorithm confusion, where the RSA public key becomes an HMAC secret. The correct design fixes the algorithm and keys in configuration, uses Spring Security's NimbusJwtDecoder instead of custom parsing, and validates iss, aud and exp, with tests that try each attack.

What to say in the interviewAbout 90 seconds aloud

Open with

The core problem is that the filter lets the token decide how it gets verified, and the attacker writes the token. That allows two well-known attacks. The first is alg none: the attacker sends a token with no signature and the code accepts it.

Then, if they want more

The second is algorithm confusion: our service verifies RS256 with the identity provider's public key, which anyone can download, so the attacker sets alg to HS256 and signs the token with HMAC, using the public key bytes as the secret. If the code then verifies HMAC with that same key, the forgery passes.

On top of that, hand-written filters usually skip the claim checks, so expired tokens or tokens meant for another service get accepted. What I would ask for in the review is to delete the filter and use Spring Security's resource server with a NimbusJwtDecoder.

The decoder gets its keys from the issuer's JWKS endpoint, accepts only RS256 because we configure it that way, and rejects any other alg before touching a key. I would add validators for issuer, expiry and audience, so a token issued for the billing service is rejected by the orders service.

And I would ask for negative tests: a none token, an HS256 token signed with the public key, an expired token and a wrong-audience token, each expecting 401. That turns the review finding into something the build keeps checking.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
RFC 7519, JSON Web Token
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A code review finds a hand-written JWT filter that decodes the token, reads the alg...": https://scrivio-interview-library.netlify.app/spring-boot/jwt/2844a69e6f/