Spring Boot Interview Questions


🔐 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:

  1. User logs in with credentials (POST /login).
  2. Server verifies username & password.
  3. If valid, server generates a JWT and sends it to the client.
  4. Client stores the JWT (e.g., in localStorage or cookies).
  5. For each subsequent request, the client sends JWT in the Authorization Header: Authorization: Bearer <jwt-token>
  6. Server validates the token → grants or denies access.

🔑 4. What is inside a JWT?

PartDescriptionExample
HeaderMetadata about the token (e.g., algorithm type).{ "alg": "HS256", "typ": "JWT" }
PayloadClaims/data about the user.{ "sub": "akshay", "role": "ADMIN" }
SignatureHash used to verify integrity.HMACSHA256(base64(header) + "." + base64(payload), secret)

🧩 5. How to implement JWT Authentication in Spring Boot?

Key components:

  1. Authentication Controller – handles login and token generation.
  2. JWT Utility Class – generates and validates tokens.
  3. JWT Filter – intercepts requests and validates JWT.
  4. Security Configuration – integrates JWT with Spring Security.

Example Flow:

POST /loginJWT 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?

FeatureAccess TokenRefresh Token
PurposeUsed to access APIsUsed to get new Access Token
ExpirationShort (e.g., 15 min)Long (e.g., 7 days)
StoredClient-sideServer or secure store
Exposure RiskHigherLower (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?

ErrorCause
JWT expiredToken lifetime exceeded
Invalid SignatureSecret key mismatch
Malformed JWTToken structure broken
403 ForbiddenMissing 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

TopicKey Point
FrameworkSpring Boot + Spring Security
Token TypeJWT (JSON Web Token)
StorageLocalStorage or HttpOnly cookie
Authentication TypeStateless
Librariesjjwt, spring-security
BenefitLightweight, 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 👉

AK Coding YouTube Channel

Share with