Bird
Raised Fist0
Spring Bootframework~15 mins

Authentication with JWT token in Spring Boot - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Authentication with JWT token
What is it?
Authentication with JWT token is a way to verify who a user is by giving them a special digital ticket called a JSON Web Token (JWT). This token is like a secure ID card that the user carries and shows to the server to prove their identity. The server checks this token instead of asking for a password every time. This method helps keep apps safe and lets users move around without logging in repeatedly.
Why it matters
Without JWT authentication, users would have to send their passwords with every request, which is unsafe and slow. It also makes it hard to build apps that work well on mobile or across many servers. JWT tokens solve this by being secure, easy to check, and stateless, meaning the server doesn't have to remember every user. This makes apps faster, safer, and easier to scale.
Where it fits
Before learning JWT authentication, you should understand basic web security concepts like sessions and cookies, and how HTTP requests work. After mastering JWT, you can explore advanced security topics like OAuth, refresh tokens, and securing microservices.
Mental Model
Core Idea
A JWT token is a secure, self-contained digital ID card that proves a user's identity without needing the server to remember them.
Think of it like...
Imagine going to a concert where you get a wristband after showing your ticket once. This wristband lets you enter and exit freely without showing your ticket again. The JWT token is like that wristband for your app.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ User logs in  │─────▶│ Server creates │─────▶│ JWT token sent │
│ with password │      │ JWT token with │      │ to user       │
└───────────────┘      │ user info     │      └───────────────┘
                       └───────────────┘
                              │
                              ▼
                     ┌───────────────────┐
                     │ User sends JWT on  │
                     │ each request       │
                     └───────────────────┘
                              │
                              ▼
                     ┌───────────────────┐
                     │ Server verifies   │
                     │ JWT token         │
                     └───────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding User Authentication Basics
🤔
Concept: Learn what authentication means and why verifying user identity is important.
Authentication is the process of checking if someone is who they say they are. Usually, this means entering a username and password. The server checks these credentials and lets the user in if they match. This is the first step to keeping apps secure.
Result
You understand that authentication confirms user identity before allowing access.
Knowing what authentication is helps you appreciate why we need secure ways like JWT to manage user identity.
2
FoundationWhat is a JWT Token?
🤔
Concept: Introduce the JSON Web Token as a secure, compact way to carry user identity data.
A JWT token is a string made of three parts: header, payload, and signature. The header says how the token is signed. The payload contains user info like ID and roles. The signature makes sure the token wasn’t changed. This token is sent to the user after login and used to prove identity later.
Result
You can identify the parts of a JWT and understand its role as a digital ID.
Understanding JWT structure is key to knowing how it securely carries user identity without passwords.
3
IntermediateCreating JWT Tokens in Spring Boot
🤔Before reading on: Do you think the server creates the JWT token before or after verifying user credentials? Commit to your answer.
Concept: Learn how to generate JWT tokens after successful user login using Spring Boot libraries.
In Spring Boot, after checking username and password, the server creates a JWT token by setting claims like username and expiration time. It then signs the token with a secret key. This token is sent back to the user to use in future requests.
Result
You can generate a JWT token in Spring Boot that securely represents a logged-in user.
Knowing when and how to create JWT tokens ensures only authenticated users get valid tokens.
4
IntermediateValidating JWT Tokens on Requests
🤔Before reading on: Do you think the server stores JWT tokens to validate them, or checks them statelessly? Commit to your answer.
Concept: Understand how the server checks JWT tokens on each request without storing session data.
When a user sends a request with a JWT token, Spring Boot extracts the token from the header. It then verifies the signature and checks claims like expiration. If valid, the server trusts the user identity inside the token without needing to look up sessions.
Result
You can validate JWT tokens statelessly, improving scalability and security.
Understanding stateless validation helps build scalable apps that don’t rely on server memory.
5
AdvancedHandling Token Expiration and Refresh
🤔Before reading on: Should expired JWT tokens be accepted or rejected? Commit to your answer.
Concept: Learn how to manage token expiration and refresh tokens to keep users logged in securely.
JWT tokens have expiration times to limit risk if stolen. When expired, users must get a new token. This is done using refresh tokens, which are long-lived and stored securely. The server verifies refresh tokens and issues new JWT tokens without asking for passwords again.
Result
You can implement token expiration and refresh logic to balance security and user convenience.
Knowing how to handle token lifecycle prevents security risks and improves user experience.
6
ExpertSecuring JWT Tokens Against Common Attacks
🤔Before reading on: Do you think storing JWT tokens in localStorage is safe or risky? Commit to your answer.
Concept: Explore advanced security practices to protect JWT tokens from theft and misuse.
JWT tokens can be stolen via cross-site scripting (XSS) if stored insecurely. Experts recommend storing tokens in HTTP-only cookies to prevent JavaScript access. Also, using short token lifetimes and rotating secrets helps. Proper CORS and HTTPS settings are essential to protect tokens in transit.
Result
You understand how to secure JWT tokens in production to prevent common vulnerabilities.
Knowing these security details protects your app from subtle but serious token theft attacks.
Under the Hood
JWT tokens are base64-encoded strings containing header, payload, and signature. The signature is created by hashing the header and payload with a secret key using algorithms like HMAC SHA256. When the server receives a token, it recalculates the signature and compares it to the token’s signature to verify integrity and authenticity. This process is stateless because the server does not store tokens; it trusts the signature and claims inside the token.
Why designed this way?
JWT was designed to be compact, URL-safe, and self-contained to work well in distributed systems and mobile apps. Traditional session storage requires server memory and synchronization, which is hard to scale. JWT’s stateless design allows easy scaling and reduces server load. The signature ensures tokens can’t be tampered with, balancing security and performance.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ Header        │─────▶│ Payload       │─────▶│ Signature     │
│ (algorithm)   │      │ (user data)   │      │ (hash with    │
│               │      │               │      │ secret key)   │
└───────────────┘      └───────────────┘      └───────────────┘
         │                     │                      │
         └─────────────┬───────┴──────────────┬───────┘
                       ▼                      ▼
               Base64 encode             Base64 encode
                       │                      │
                       └──────────────┬───────┘
                                      ▼
                             JWT token string
                                      │
                                      ▼
                       Server verifies signature
                       by hashing header+payload
                       and comparing with signature
Myth Busters - 4 Common Misconceptions
Quick: Do you think JWT tokens must be stored on the server to work? Commit yes or no.
Common Belief:JWT tokens require server-side storage like sessions to validate users.
Tap to reveal reality
Reality:JWT tokens are stateless and do not require server storage; validation happens by checking the token’s signature.
Why it matters:Believing this leads to unnecessary server memory use and complexity, losing JWT’s scalability benefits.
Quick: Do you think JWT tokens are encrypted by default? Commit yes or no.
Common Belief:JWT tokens hide user data because they are encrypted.
Tap to reveal reality
Reality:JWT tokens are only base64 encoded, not encrypted, so anyone with the token can read the payload.
Why it matters:Assuming encryption causes developers to put sensitive data in tokens, risking data leaks.
Quick: Do you think storing JWT tokens in localStorage is safe from all attacks? Commit yes or no.
Common Belief:Storing JWT tokens in localStorage is safe and convenient.
Tap to reveal reality
Reality:LocalStorage is vulnerable to cross-site scripting (XSS) attacks, which can steal tokens.
Why it matters:Ignoring this risk can lead to token theft and account compromise.
Quick: Do you think JWT tokens can be invalidated before expiration easily? Commit yes or no.
Common Belief:JWT tokens can be instantly revoked by the server anytime.
Tap to reveal reality
Reality:JWT tokens are stateless and cannot be revoked without extra mechanisms like token blacklists.
Why it matters:Misunderstanding this can cause security holes if stolen tokens remain valid until expiry.
Expert Zone
1
JWT tokens should avoid storing sensitive data because payloads are readable; use them only for identity claims.
2
Token signature algorithms matter: using weak algorithms like none or outdated hashes can break security.
3
Refresh tokens must be stored and handled more securely than access tokens because they allow new token creation.
When NOT to use
JWT is not ideal when you need immediate token revocation or very short-lived sessions; traditional server sessions or opaque tokens with server storage are better alternatives.
Production Patterns
In production, JWT tokens are often combined with HTTPS, stored in HTTP-only cookies, and paired with refresh tokens. Servers use filters or middleware to validate tokens on each request, and secrets are rotated regularly to maintain security.
Connections
OAuth 2.0
JWT tokens are often used as access tokens within OAuth 2.0 flows.
Understanding JWT helps grasp how OAuth securely delegates access without sharing passwords.
Stateless Protocols
JWT enables stateless authentication, fitting well with stateless protocols like HTTP.
Knowing stateless design principles clarifies why JWT scales better than session-based methods.
Digital Signatures in Cryptography
JWT signatures use cryptographic hashes to ensure token integrity and authenticity.
Understanding digital signatures in cryptography deepens trust in JWT’s security model.
Common Pitfalls
#1Storing JWT tokens in localStorage exposing them to XSS attacks.
Wrong approach:localStorage.setItem('token', jwtToken);
Correct approach:Set JWT token in HTTP-only, Secure cookie via server response headers.
Root cause:Misunderstanding that localStorage is accessible by JavaScript and vulnerable to malicious scripts.
#2Putting sensitive user data like passwords inside JWT payload.
Wrong approach:{ "sub": "user123", "password": "secret" }
Correct approach:{ "sub": "user123", "roles": ["USER"] }
Root cause:Assuming JWT payload is encrypted and private, rather than just encoded.
#3Not verifying JWT signature on incoming requests.
Wrong approach:Accepting JWT token payload without signature check.
Correct approach:Use JWT library to verify signature with secret key before trusting token data.
Root cause:Underestimating the importance of signature verification for token integrity.
Key Takeaways
JWT tokens are self-contained digital IDs that let servers verify users without storing sessions.
They carry user info in a readable format but are protected by a signature to prevent tampering.
Proper creation, validation, and secure storage of JWT tokens are essential for safe authentication.
JWT’s stateless nature makes it scalable but requires careful handling of expiration and revocation.
Understanding JWT security nuances prevents common vulnerabilities like token theft and misuse.

Practice

(1/5)
1. What is the main purpose of using a JWT token in Spring Boot authentication?
easy
A. To store user passwords in the database
B. To securely transmit user identity without sending passwords every time
C. To encrypt the entire application data
D. To replace the need for HTTPS

Solution

  1. Step 1: Understand JWT token role

    JWT tokens are used to prove user identity securely without resending passwords.
  2. Step 2: Compare options with JWT purpose

    Only To securely transmit user identity without sending passwords every time correctly describes this purpose; others are unrelated or incorrect.
  3. Final Answer:

    To securely transmit user identity without sending passwords every time -> Option B
  4. Quick Check:

    JWT token purpose = secure identity proof [OK]
Hint: JWT tokens prove identity without passwords [OK]
Common Mistakes:
  • Thinking JWT stores passwords
  • Confusing JWT with data encryption
  • Assuming JWT replaces HTTPS
2. Which of the following is the correct way to extract the JWT token from an HTTP request header in Spring Boot?
easy
A. String token = request.getParameter("Authorization");
B. String token = request.getCookie("jwt");
C. String token = request.getBody();
D. String token = request.getHeader("Authorization").substring(7);

Solution

  1. Step 1: Identify JWT token location in HTTP request

    JWT tokens are usually sent in the Authorization header with prefix "Bearer ".
  2. Step 2: Extract token correctly

    String token = request.getHeader("Authorization").substring(7); extracts the header and removes the "Bearer " prefix (7 characters), which is correct.
  3. Final Answer:

    String token = request.getHeader("Authorization").substring(7); -> Option D
  4. Quick Check:

    Extract JWT from Authorization header [OK]
Hint: JWT is in Authorization header with 'Bearer ' prefix [OK]
Common Mistakes:
  • Using request parameters instead of headers
  • Trying to get token from request body
  • Assuming token is in cookies by default
3. Given this Spring Boot JWT validation snippet, what will be the output if the token is expired?
try {
  Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
  System.out.println("Token is valid");
} catch (ExpiredJwtException e) {
  System.out.println("Token expired");
} catch (JwtException e) {
  System.out.println("Invalid token");
}
medium
A. Invalid token
B. Token is valid
C. Token expired
D. No output

Solution

  1. Step 1: Understand exception handling in JWT parsing

    If the token is expired, the parser throws ExpiredJwtException, caught by the first catch block.
  2. Step 2: Identify printed output for expired token

    The catch block prints "Token expired" when ExpiredJwtException occurs.
  3. Final Answer:

    Token expired -> Option C
  4. Quick Check:

    Expired token triggers ExpiredJwtException [OK]
Hint: ExpiredJwtException means token expired [OK]
Common Mistakes:
  • Confusing expired token with invalid token
  • Ignoring exception handling order
  • Assuming no output on exceptions
4. Identify the error in this JWT token generation code snippet in Spring Boot:
String token = Jwts.builder()
  .setSubject(username)
  .signWith(SignatureAlgorithm.HS256, secretKey)
  .compact();
medium
A. Incorrect method to set signing key in new jjwt versions
B. Missing call to build() before compact()
C. Username should not be set as subject
D. Missing token expiration setting

Solution

  1. Step 1: Check jjwt signing method usage

    In recent jjwt versions, signWith requires a Key object, not just algorithm and string key.
  2. Step 2: Identify correct signing method

    Using signWith(SignatureAlgorithm, String) is deprecated and causes errors; must use signWith(Key).
  3. Final Answer:

    Incorrect method to set signing key in new jjwt versions -> Option A
  4. Quick Check:

    Use Key object with signWith in jjwt [OK]
Hint: Use Key object, not algorithm + string, in signWith [OK]
Common Mistakes:
  • Ignoring jjwt version changes
  • Assuming string key is accepted directly
  • Confusing expiration with signing errors
5. You want to implement JWT authentication in Spring Boot that automatically rejects tokens older than 15 minutes and refreshes tokens on each valid request. Which approach correctly combines expiration and refresh logic?
hard
A. Set token expiration to 15 minutes and issue a new token with updated expiration on each valid request
B. Set token expiration to 15 minutes and never refresh tokens; force user to login again after expiry
C. Set token expiration to 1 hour and refresh tokens only when user logs out
D. Do not set expiration and refresh tokens every time to keep user logged in indefinitely

Solution

  1. Step 1: Understand token expiration and refresh needs

    To reject tokens older than 15 minutes, set expiration to 15 minutes.
  2. Step 2: Implement refresh on each valid request

    Issuing a new token with updated expiration on each valid request keeps user session active securely.
  3. Final Answer:

    Set token expiration to 15 minutes and issue a new token with updated expiration on each valid request -> Option A
  4. Quick Check:

    Short expiration + refresh token = secure session [OK]
Hint: Short expiration plus refresh token on requests [OK]
Common Mistakes:
  • Not refreshing tokens causing forced logouts
  • Setting too long expiration risking security
  • Ignoring expiration causing infinite sessions