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

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