JWT Authentication in Spring Boot Explained with Real Examples

Modern applications are increasingly built using REST APIs and microservices. Traditional session-based authentication is often not suitable for these architectures.


JWT (JSON Web Token) is one of the most popular solutions for securing REST APIs and is widely used in Spring Boot applications.


What is JWT?

JWT stands for JSON Web Token. It is a compact and self-contained token used to securely transmit user information between client and server.

After successful authentication, the server generates a JWT token and returns it to the client.


Why Do We Need JWT?

Consider a REST API accessed by mobile applications, web applications and third-party clients.

Using HTTP sessions becomes difficult because the server must maintain session information.

JWT solves this problem by storing user information inside the token itself.


JWT Authentication Flow


User Login
     |
     v
Authentication
     |
     v
Generate JWT
     |
     v
Return JWT
     |
     v
Store JWT
     |
     v
Send JWT with Requests
     |
     v
Validate JWT
     |
     v
Access Protected APIs

Real World Example

A customer logs into an e-commerce application.


Username:
john

Password:
password123

Credentials are validated successfully.

Spring Boot generates a JWT token.


eyJhbGciOiJIUzI1NiJ9...

The client stores this token and uses it for future requests.


JWT Structure

A JWT token contains three parts.


Header

Payload

Signature

Example


xxxxx.yyyyy.zzzzz

Header

The header contains token metadata.


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

Payload

The payload contains claims.


{
  "sub": "john",
  "role": "USER"
}

This is where user-related data is stored.


Signature

The signature ensures token integrity.

If the token is modified, signature validation fails.


Add Required Dependency


<dependency>
    <groupId>
        io.jsonwebtoken
    </groupId>

    <artifactId>
        jjwt-api
    </artifactId>

    <version>
        0.11.5
    </version>
</dependency>

Generating JWT Token


public String generateToken(
        String username) {

    return Jwts.builder()

        .setSubject(username)

        .setIssuedAt(
            new Date()
        )

        .setExpiration(
            new Date(
                System.currentTimeMillis()
                + 86400000
            )
        )

        .signWith(
            SECRET_KEY
        )

        .compact();
}

This creates a token valid for 24 hours.


Validating JWT Token


public boolean validateToken(
        String token) {

    try {

        Jwts.parserBuilder()

            .setSigningKey(
                SECRET_KEY
            )

            .build()

            .parseClaimsJws(
                token
            );

        return true;

    }
    catch(Exception ex) {

        return false;

    }
}

Sending JWT in Requests

JWT is usually sent using the Authorization header.


Authorization:

Bearer
eyJhbGciOiJIUzI1NiJ9...

Spring Security JWT Flow


Client
   |
   v
JWT Filter
   |
   v
Validate Token
   |
   v
Security Context
   |
   v
Controller

Every request passes through a JWT filter before reaching the controller.


JWT Filter Example


public class JwtAuthenticationFilter
extends OncePerRequestFilter {

}

This filter extracts and validates the JWT token.


Benefits of JWT

  • Stateless Authentication
  • Scalable Architecture
  • Microservices Friendly
  • Reduced Server Memory Usage
  • Widely Supported

Limitations of JWT

  • Token Revocation Complexity
  • Payload Visibility
  • Larger Request Size
  • Secret Key Management Required

JWT vs Session-Based Authentication

JWT Session
Stateless Stateful
Scalable Requires Session Storage
API Friendly Web Applications
Popular for Microservices Traditional Applications

Common Interview Questions

What is JWT?

A JSON Web Token used for secure authentication and authorization.


What are the three parts of JWT?

Header, Payload and Signature.


Is JWT encrypted?

No. JWT is encoded and signed, not encrypted by default.


Why use JWT in REST APIs?

Because it provides stateless authentication and good scalability.


Where is JWT stored?

Typically inside local storage, session storage or HTTP-only cookies.


Best Practices

  • Keep token expiration short.
  • Use HTTPS.
  • Never store sensitive information in payload.
  • Protect secret keys.
  • Implement refresh token strategy.

Frequently Asked Questions (FAQ)

Can JWT contain roles?

Yes. Roles and permissions can be included in claims.


Can JWT be used with Spring Security?

Yes. Spring Security commonly integrates with JWT authentication.


Is JWT suitable for microservices?

Yes. JWT is widely used in microservice architectures.


Conclusion

JWT Authentication has become the standard approach for securing REST APIs and microservices. Understanding token generation, validation, filters, claims and SecurityContext integration is essential for building secure Spring Boot applications and succeeding in modern Java interviews.


Keywords

JWT Authentication, Spring Boot JWT, Spring Security JWT, JSON Web Token, JWT Tutorial, JWT Interview Questions, Spring Boot Security, JWT Filter, Stateless Authentication, JWT Authentication Example, REST API Security, Microservices Security, Spring Security Tutorial, Java Backend Security, Enterprise Java Development



JWT Authentication in Spring Boot Explained with Real Examples JWT Authentication in Spring Boot Explained with Real Examples Reviewed by 13thGhost on 12:36 PM Rating: 5

Recommended Posts

Powered by Blogger.