← Back to Questions
Spring Boot

What is JWT authentication in Spring Boot?

Learn What is JWT authentication in Spring Boot? with simple explanations, real-time examples, interview tips and practical use cases.

What is JWT Authentication in Spring Boot?

JWT Authentication in Spring Boot is a stateless authentication mechanism where users are authenticated using JSON Web Tokens (JWT) instead of traditional server-side sessions.

After successful login, the server generates a JWT token and sends it to the client. The client includes this token in future requests for authentication and authorization.

In simple words, JWT authentication allows users to access secured APIs using tokens instead of storing sessions on the server.


What is JWT?

JWT stands for:

JSON Web Token

JWT is an open standard used to securely transfer user information between client and server in the form of digitally signed tokens.


Why JWT Authentication is Used

Traditional session-based authentication has limitations:

  • Server must store sessions
  • Scaling becomes difficult
  • Microservices integration becomes complex
  • Frontend and backend separation becomes harder

JWT solves these problems by providing:

  • Stateless authentication
  • Better scalability
  • Microservices support
  • Frontend-backend separation
  • Mobile app compatibility

Real-Life JWT Example

Consider airport security:

  • User identity is verified at check-in
  • Boarding pass is issued
  • User shows boarding pass at checkpoints

Here:

  • User login → Authentication
  • Boarding pass → JWT Token
  • Checkpoint verification → Token validation

How JWT Authentication Works

JWT authentication flow:

  1. User sends username and password
  2. Server validates credentials
  3. Server generates JWT token
  4. Client stores JWT token
  5. Client sends token in every request
  6. Server validates token
  7. Access is granted

JWT Authentication Architecture


Client → Login Request → Spring Boot API

Spring Boot → Generates JWT Token

Client → Stores Token

Client → Sends Token in Headers

Spring Security → Validates JWT

Access Granted

JWT Token Structure

JWT token contains three parts:

HEADER.PAYLOAD.SIGNATURE

1. Header

Header contains token metadata.

Example

{
   "alg": "HS256",
   "typ": "JWT"
}

2. Payload

Payload contains user information and claims.

Example

{
   "sub": "naresh",
   "roles": ["ROLE_ADMIN"],
   "exp": 1740000000
}

3. Signature

Signature ensures token integrity and security.

It is generated using:

  • Header
  • Payload
  • Secret key

Complete JWT Example


eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiJuYXJlc2giLCJyb2xlcyI6WyJST0xFX0FETUlOIl19
.
XhKJ3jskdkslwe834kjsdf9w...

Spring Boot JWT Dependencies

Spring Security Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

JWT Dependency

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.5</version>
</dependency>

JWT Authentication Flow in Spring Boot

Step Description
1 User sends login credentials
2 Spring Security authenticates user
3 JWT token is generated
4 Client stores token
5 Client sends token in every request
6 JWT filter validates token
7 Request is processed

JWT Token Generation Example

public String generateToken(String username) {

    return Jwts.builder()
            .setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(
                    new Date(
                            System.currentTimeMillis()
                            + 1000 * 60 * 60
                    )
            )
            .signWith(
                    Keys.hmacShaKeyFor(
                            SECRET_KEY.getBytes()
                    ),
                    SignatureAlgorithm.HS256
            )
            .compact();
}

JWT Token Validation Example

public String extractUsername(String token) {

    return Jwts.parserBuilder()
            .setSigningKey(
                    Keys.hmacShaKeyFor(
                            SECRET_KEY.getBytes()
                    )
            )
            .build()
            .parseClaimsJws(token)
            .getBody()
            .getSubject();
}

JWT Authentication Filter

JWT filter intercepts requests and validates tokens.

Example

public class JwtAuthFilter
        extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain)
            throws ServletException, IOException {

        String authHeader =
                request.getHeader("Authorization");

        if(authHeader != null
                && authHeader.startsWith("Bearer ")) {

            String token =
                    authHeader.substring(7);

            // validate token
        }

        filterChain.doFilter(request, response);
    }
}

Authorization Header Example

Authorization: Bearer eyJhbGciOiJIUzI1Ni...

Spring Security JWT Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/auth/**")
                .permitAll()
                .anyRequest()
                .authenticated()
            );

        return http.build();
    }
}

Why CSRF is Disabled in JWT

JWT authentication is stateless.

Since sessions are not used:

  • CSRF protection is usually disabled
  • JWT tokens are validated in headers

What is Stateless Authentication?

Stateless authentication means:

  • Server does not store user session
  • Every request contains authentication token
  • Each request is independently verified

Session Authentication vs JWT Authentication

Feature Session Authentication JWT Authentication
State Stateful Stateless
Storage Server Session Client Token
Scalability Moderate High
Microservices Support Limited Excellent

What is Refresh Token?

Access tokens usually expire quickly.

Refresh tokens help generate new access tokens without requiring login again.


JWT Security Best Practices

  • Use HTTPS always
  • Store secret keys securely
  • Use short token expiration
  • Implement refresh tokens
  • Never store sensitive data inside JWT
  • Validate tokens properly
  • Use strong secret keys

Common JWT Exceptions

Exception Description
ExpiredJwtException JWT token expired
MalformedJwtException Invalid JWT format
SignatureException Invalid JWT signature

Advantages of JWT Authentication

  • Stateless authentication
  • Highly scalable
  • Ideal for microservices
  • Supports mobile applications
  • No server-side session storage
  • Frontend-backend separation support

Disadvantages of JWT Authentication

  • Token revocation is difficult
  • Large payload increases token size
  • Improper secret handling may cause vulnerabilities
  • Refresh token implementation adds complexity

Real-Time Example in Banking Application

Banking JWT authentication flow:

  1. User logs in using credentials
  2. Server validates user
  3. JWT token is generated
  4. User accesses transfer APIs using token
  5. Spring Security validates token for every request

JWT Authentication in Microservices

JWT is highly popular in microservices because:

  • Services remain stateless
  • No centralized session management required
  • Easy service-to-service authentication
  • Better scalability in cloud environments

Common Interview Questions on JWT Authentication

What is JWT authentication?

JWT authentication is a token-based stateless authentication mechanism where users access APIs using JWT tokens.

What are the three parts of JWT?

Header, Payload, and Signature.

Why is JWT called stateless?

Because the server does not store session information.

Why is JWT popular in microservices?

JWT supports scalability, stateless communication, and distributed authentication.

What is the difference between access token and refresh token?

Access token is used for API access, while refresh token generates new access tokens.


Conclusion

JWT authentication is one of the most widely used authentication mechanisms in modern Spring Boot applications.

It provides stateless authentication, better scalability, microservices compatibility, and secure API access.

Spring Security integrates seamlessly with JWT to build secure REST APIs, enterprise systems, and cloud-native applications.

Understanding JWT authentication is essential for Spring Boot developers because it is heavily used in modern backend development, mobile applications, microservices, and enterprise-grade security architectures.

Why this Spring Boot question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.