JWT Authentication in Spring Boot Explained with Real-Time Examples
Introduction :
In the previous article, we learned the basics of Spring Security, including Authentication, Authorization, and Security Configuration.
While Basic Authentication is useful for learning, modern applications rarely use it in production. Instead, most REST APIs use JWT (JSON Web Token) Authentication because it is secure, scalable, and stateless.
When working on REST APIs, I noticed that applications need a way to verify users without maintaining sessions on the server. This is where JWT becomes extremely useful.
In this article, we'll understand JWT Authentication, how JWT tokens work, and how to implement JWT-based security in a Spring Boot application using real-time examples.
What is JWT?
JWT stands for JSON Web Token.
It is a compact and secure token used to exchange information between a client and a server.
A JWT token contains encoded user information and is digitally signed to prevent tampering.
Instead of storing user sessions on the server, the client stores the JWT token and sends it with every request.
Why Do We Need JWT?
Consider an Employee Management System.
Without JWT:
User logs in.
Server creates a session.
Server stores session information.
Every request depends on server-side sessions.
Problems:
Difficult to scale
More memory usage
Not ideal for microservices
With JWT:
User logs in.
Server generates a token.
Client stores the token.
Client sends the token with every request.
Benefits:
Stateless Authentication
Better Performance
Scalable Architecture
Ideal for REST APIs
Real-Time Example
Imagine a Banking Application.
Login Request
POST /login
User sends:
{
"username": "Sulochana",
"password": "password123"
}
Server validates credentials and generates a JWT token.
eyJhbGciOiJIUzI1NiJ9...
The client stores the token.
For future requests:
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
The server validates the token before processing the request.
Structure of JWT
A JWT consists of three parts:
Header.Payload.Signature
Example:
eyJhbGciOiJIUzI1NiJ9
.
eyJzdWIiOiJqb2huIn0
.
sdfghjk123456789
Header
Contains token type and algorithm.
{
"alg": "HS256",
"typ": "JWT"
}
Payload
Contains user information.
{
"sub": "Sulochana",
"role": "ADMIN"
}
Signature
Used to verify token integrity.
Adding JWT Dependencies
Add the following dependencies:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
Creating JWT Utility Class
Create a utility class to generate tokens.
@Component
public class JwtUtil {
private final String SECRET_KEY =
"mySecretKeyForJwtAuthentication";
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();
}
}
This generates a token valid for one hour.
Generating JWT Token
Example:
String token =
jwtUtil.generateToken("Sulochana");
Output:
eyJhbGciOiJIUzI1NiJ9...
The token is sent back to the client after successful login.
Validating JWT Token
public String extractUsername(
String token) {
return Jwts.parserBuilder()
.setSigningKey(
Keys.hmacShaKeyFor(
SECRET_KEY.getBytes()))
.build()
.parseClaimsJws(token)
.getBody()
.getSubject();
}
Spring Security uses this information to verify user identity.
Security Configuration
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http)
throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login")
.permitAll()
.anyRequest()
.authenticated()
);
return http.build();
}
Explanation:
Login endpoint is public.
All other endpoints require authentication.
JWT Authentication Flow
Step 1
User sends username and password.
POST /login
Step 2
Server validates credentials.
Step 3
Server generates JWT token.
eyJhbGciOiJIUzI1NiJ9...
Step 4
Client stores token.
Step 5
Client sends token with every request.
Authorization: Bearer token
Step 6
Server validates token and grants access.
Common Mistakes Beginners Make
Storing Sensitive Information
Never store passwords inside JWT payloads.
Long Expiration Times
Avoid tokens that never expire.
Exposing Secret Keys
Store secret keys securely using configuration files or environment variables.
Skipping Token Validation
Always validate tokens before granting access.
JWT Authentication Interview Questions
What is JWT?
JWT is a compact token format used for secure authentication and information exchange.
Why is JWT preferred in REST APIs?
Because it is stateless, scalable, and suitable for distributed systems.
What are the three parts of JWT?
Header
Payload
Signature
What is the purpose of the Signature?
To verify token integrity and prevent tampering.
What is Bearer Token?
A JWT token sent in the Authorization header.
Conclusion :
JWT Authentication is one of the most commonly used security mechanisms in modern Spring Boot applications. It enables secure, stateless authentication and works exceptionally well with REST APIs and microservices.
In this article, we learned how JWT works, explored its structure, generated tokens, validated requests, and integrated JWT concepts with Spring Security.
Now that we understand JWT Authentication, the next step is implementing Role-Based Access Control (RBAC) using Spring Security.
In the next article, we'll learn how to create roles such as ADMIN, MANAGER, and USER, restrict API access based on roles, and build secure enterprise-grade applications using Spring Security.

Comments
Post a Comment