Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท JWT and OAuth2 Resource Server

Signing and Validating JWTs

Sign and verify JWTs the safe way: HMAC versus RSA keys, constant-time comparison, expiry and clock skew, and why the alg none and algorithm confusion attacks work.

A JWT is only as trustworthy as the checks a server runs on it. Spring Security's NimbusJwtDecoder does these checks for you, but you should know what they are, because most JWT vulnerabilities come from skipping one of them. This lesson builds a small signer and verifier in plain Java (a labelled stand-in: the real framework code cannot run on this site) and then shows two classic attacks.

Symmetric or asymmetric signing

Algorithm Key Who can create tokens Who can verify
HS256 (HMAC-SHA256) One shared secret Anyone holding the secret Anyone holding the secret
RS256 (RSA + SHA-256) Private and public key Only the holder of the private key Anyone with the public key
ES256 (ECDSA P-256) Private and public key Only the private key holder Anyone with the public key

Use HS256 when one application both issues and verifies tokens. Use RS256 or ES256 when several services verify tokens issued by a separate authorization server: the resource servers only need the public key, so a leak of one of them cannot forge tokens.

In Spring Security the same choice looks like this (read-only, real API):

Java
// HS256: one shared secret (Spring Security 6/7 with the Nimbus library)
@Bean
JwtDecoder jwtDecoder(@Value("${app.jwt.secret}") String secret) {
    SecretKey key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    return NimbusJwtDecoder.withSecretKey(key).build();
}

// RS256: public key only, or fetch keys from the issuer's JWK Set URI
@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri("https://auth.example.com/.well-known/jwks.json").build();
}

A signer and a strict verifier

A correct verifier performs these steps in order:

  1. Split into exactly three parts.
  2. Parse the header and require the algorithm you expect.
  3. Recompute the signature and compare in constant time.
  4. Only then read claims and check exp, nbf, and (for real systems) iss and aud.
Java Sign and verify with expiry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two details matter here:

  • MessageDigest.isEqual compares in constant time. A normal equals stops at the first different byte, and an attacker can measure that tiny difference to guess a signature one byte at a time.
  • Clock skew. Servers' clocks drift, so Spring's default validator allows 60 seconds of skew on exp and nbf. The stand-in does the same. You can change it with JwtTimestampValidator(Duration).

Attack 1: the alg: none token

The JWT standard allows an unsigned token whose header says "alg":"none". Early libraries obeyed the header, so an attacker could send a token with any claims and an empty signature, and the server accepted it. The cure is simple: the server decides the algorithm, never the token.

Attack 2: algorithm confusion

Suppose a service verifies RS256 tokens with its public key, which is public by design. If the verifier trusts the header, an attacker can write "alg":"HS256" and sign the token with HMAC, using the public key bytes as the secret. The verifier then calls HMAC with the public key and the signature matches. The cure is the same: pin the algorithm.

Java A naive verifier versus a pinned one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Output:

TEXT
naive  accepts forged alg=none token: true
pinned accepts forged alg=none token: false
pinned accepts honest token         : true

Spring's NimbusJwtDecoder is built with a specific JWSAlgorithm and rejects everything else, and it never accepts none. You get that safety by using the framework decoder instead of parsing tokens yourself.

Never write your own JWT parsing in production. The runnable code in this lesson exists to teach the checks. Use NimbusJwtDecoder (or another maintained library) and keep it updated.

Key hygiene

  • HS256 secrets must be random and at least 32 bytes. A short, guessable secret can be brute-forced offline from any token you have seen.
  • Store secrets in environment variables or a secret manager, never in the repository.
  • Publish rotating public keys at a JWK Set URI and put a kid (key id) in the header so verifiers pick the right key during rotation.
  • Add iss and aud validators so a token meant for another service is refused. See Resource server configuration.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should signature comparison be constant-time?

    A comparison that stops at the first mismatch leaks timing information an attacker can use to guess the signature.
  2. 2. Which party should decide the verification algorithm?

    Trusting the header enables the alg none and algorithm confusion attacks. The server pins the algorithm.
  3. 3. When is RS256 preferable to HS256?

    With RS256 only the private key holder can sign. Verifiers need just the public key.
  4. 4. What does clock skew tolerance do?

    It accepts tokens a few seconds past exp (by default 60 s in Spring) so slightly different clocks do not cause random failures.

Summary

  • Verify in this order: structure, algorithm, signature (constant-time), then claims.
  • HS256 uses one shared secret; RS256 and ES256 separate signing from verifying.
  • The server pins the algorithm; alg: none and algorithm confusion attacks exploit verifiers that trust the header.
  • Allow only small clock skew and use strong, rotated keys.
  • Use the framework decoder, not hand-written code, in production.

Next: Resource server configuration