Hi ๐, I’m Anandharaj.
Today’s Learnings : JWT Token Validation in Spring Security
๐น Always Spring Security gives confusion to me.
So I’m sharing my learnings on how a JWT token is validated when a request comes in.
๐ What happens when a request comes in?
1️⃣ Incoming request with a token
When a request hits your API, Spring Security’s filter chain intercepts it and extracts the token from the Authorization
header (usually in the format: Bearer <token>
).
2️⃣ Check token type
The filter checks if it’s a Bearer
token and then hands it over to a configured JWT decoder.
๐ JWT Structure
A JWT has three parts, separated by dots (.
):
-
Header ๐ contains metadata (e.g., algorithm:
HS256
,RS256
) -
Payload ๐ contains claims (user info, expiry time, issuer, audience, etc.)
-
Signature ๐ ensures integrity and authenticity
๐ Header and Payload are Base64URL‑encoded and readable.
๐ Signature is cryptographically generated and cannot be reverse‑engineered.
๐ How Spring validates a JWT
✔️ Step 1: Decoder setup
When your Spring Boot app starts, it uses a configured JwtDecoder
.
For example:
-
The
JwtDecoder
is initialized with trusted details (like public keys or JWK Set URIs) from your identity provider. -
These details are usually cached by Spring for performance.
✔️ Step 2: Validation process
When a token arrives:
-
Header & Payload validation:
The decoder checks claims likeexp
(expiry),iss
(issuer),aud
(audience) against the trusted configuration. -
Signature validation:
Using the public key (fetched from the trusted issuer during app startup), Spring recalculates the signature from the header and payload and compares it with the signature part of the token.
✅ If everything matches, the token is valid.
❌ If not, access is denied.
๐ก Key Takeaways
✅ Always configure a JwtDecoder
that matches the way your tokens are generated (e.g., RS256 → use a JWK set URI from your identity provider).
✅ Remember the three parts of a JWT – only header and payload are human-readable; the signature is cryptographically protected.
✅ Spring Security handles this flow through its filter chain and caching, so you rarely need to manually decode tokens.
๐ฅ Bonus Tip
If you want to inspect a token manually, try https://jwt.io.
Paste your token, and you’ll see the header, payload, and whether the signature is verified (see my screenshot above).
✍️ This was a quick note from my daily learnings.
If you’ve struggled with JWT validation, hope this helps you understand the flow better! ๐
Comments
Post a Comment