🔐 JWT Authentication with Spring Boot — Question (2025 Edition)
🧠 1. What is JWT?
JWT (JSON Web Token) is a compact, URL-safe token used to securely transmit information between a client and server.
It is commonly used for authentication and authorization in REST APIs.
A JWT consists of three parts:
Header.Payload.Signature
Example:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJha3NoYXkiLCJyb2xlIjoiQURNSU4ifQ.XYZ123abc
⚙️ 2. Why use JWT in Spring Boot?
Because it helps build stateless authentication systems:
- No need to store sessions on the server.
- Works perfectly with REST APIs and microservices.
- Reduces overhead and increases scalability.
🏗️ 3. How does JWT authentication flow work?
Step-by-step process:
- User logs in with credentials (
POST /login). - Server verifies username & password.
- If valid, server generates a JWT and sends it to the client.
- Client stores the JWT (e.g., in localStorage or cookies).
- For each subsequent request, the client sends JWT in the Authorization Header:
Authorization: Bearer <jwt-token> - Server validates the token → grants or denies access.
🔑 4. What is inside a JWT?
| Part | Description | Example |
|---|---|---|
| Header | Metadata about the token (e.g., algorithm type). | { "alg": "HS256", "typ": "JWT" } |
| Payload | Claims/data about the user. | { "sub": "akshay", "role": "ADMIN" } |
| Signature | Hash used to verify integrity. | HMACSHA256(base64(header) + "." + base64(payload), secret) |
🧩 5. How to implement JWT Authentication in Spring Boot?
Key components:
- Authentication Controller – handles login and token generation.
- JWT Utility Class – generates and validates tokens.
- JWT Filter – intercepts requests and validates JWT.
- Security Configuration – integrates JWT with Spring Security.
Example Flow:
POST /login → JWT generated
→ Add Authorization header
→ Access protected APIs
🔐 6. Where to store the JWT token?
- Frontend (Browser):
localStorage→ easier, but vulnerable to XSS.HttpOnly Cookie→ safer (prevents XSS).
- Mobile apps / Microservices: store in secure vaults or headers.
⏳ 7. How do you handle JWT expiration?
JWTs usually have a limited lifespan:
{
"sub": "akshay",
"exp": 1735707600
}
When expired, you can:
- Use a refresh token mechanism.
- Force user to log in again.
- Implement token rotation for better security.
🧾 8. What is the difference between Access Token and Refresh Token?
| Feature | Access Token | Refresh Token |
|---|---|---|
| Purpose | Used to access APIs | Used to get new Access Token |
| Expiration | Short (e.g., 15 min) | Long (e.g., 7 days) |
| Stored | Client-side | Server or secure store |
| Exposure Risk | Higher | Lower (used rarely) |
🧰 9. What dependencies are used in Spring Boot JWT implementation?
Add in pom.xml:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
🔍 10. How to validate a JWT token in Spring Boot?
Use a JWT Filter class:
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
if (jwtUtil.validateToken(token)) {
// Set authentication in context
}
}
🛡️ 11. How to secure endpoints in Spring Boot?
Use Spring Security’s HttpSecurity configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.requestMatchers("/login", "/register").permitAll()
.anyRequest().authenticated();
}
🔒 12. What are common security best practices?
✅ Use HTTPS (never send tokens over HTTP).
✅ Keep JWT short-lived.
✅ Store secret keys securely.
✅ Rotate secrets periodically.
✅ Use refresh tokens for long sessions.
✅ Validate issuer, audience, and expiration fields.
🧠 13. What are common errors in JWT Authentication?
| Error | Cause |
|---|---|
JWT expired | Token lifetime exceeded |
Invalid Signature | Secret key mismatch |
Malformed JWT | Token structure broken |
403 Forbidden | Missing or invalid token in header |
🧩 14. Can JWT be revoked?
JWTs are stateless, so they can’t be easily revoked.
You can:
- Maintain a token blacklist (in DB/Redis).
- Rotate keys to invalidate old tokens.
- Use short expiry + refresh mechanism.
⚡ 15. What are the main advantages of JWT?
✅ Stateless — no server memory required
✅ Compact and fast to transfer
✅ Works across domains (ideal for microservices)
✅ Easy to debug and verify
✅ Supported by most frameworks & languages
🧩 Example Token (Decoded)
{
"sub": "akshay",
"role": "ADMIN",
"iat": 1735750000,
"exp": 1735753600
}
🎯 Summary
| Topic | Key Point |
|---|---|
| Framework | Spring Boot + Spring Security |
| Token Type | JWT (JSON Web Token) |
| Storage | LocalStorage or HttpOnly cookie |
| Authentication Type | Stateless |
| Libraries | jjwt, spring-security |
| Benefit | Lightweight, scalable, secure |
Read other awesome articles in Medium.com or in akcoding’s posts.
OR
Join us on YouTube Channel
OR Scan the QR Code to Directly open the Channel 👉

