JWT Authentication in Spring Boot with Spring Security
Introduction
Modern web applications require secure and scalable authentication mechanisms. Traditional session-based authentication works well for server-rendered applications, but REST APIs are typically stateless and need a different approach.
JSON Web Token (JWT) is one of the most widely used authentication methods for securing Spring Boot REST APIs. After a user logs in successfully, the server generates a signed token. The client includes this token in future requests, allowing the server to verify the user's identity without storing session data.
In this tutorial, you'll learn how JWT authentication works, how to configure it with Spring Security, and the best practices for building secure REST APIs.
What is JWT?
JWT (JSON Web Token) is a compact, URL-safe token used to securely transmit information between two parties.
A JWT is digitally signed, making it difficult to modify without detection.
Instead of storing user sessions on the server, the client stores the token and sends it with each request.
Why Use JWT?
JWT is popular because it is:
- Stateless
- Lightweight
- Secure
- Easy to integrate with REST APIs
- Supported by many programming languages
Common use cases include:
- Mobile applications
- Single Page Applications (SPA)
- Microservices
- REST APIs
- Cloud-native applications
JWT Authentication Flow
User Login ↓ Username & Password ↓ Authentication Manager ↓ Credentials Valid? ↙ ↘ No Yes ↓ ↓ 401 Generate JWT ↓ Send Token to Client ↓ Client Stores Token ↓ Future Requests ↓ Authorization Header ↓ Server Validates JWT ↓ Protected Resource
JWT Structure
A JWT consists of three parts:
Header.Payload.Signature
Example:
eyJhbGciOiJIUzI1NiJ9. eyJzdWIiOiJ6ZWVzaGFuIn0. SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Header
Contains metadata about the token.
Example:
{ "alg":"HS256", "typ":"JWT" }
Payload
Contains claims such as:
{ "sub":"admin", "role":"ADMIN", "exp":1755000000 }
Never store sensitive information like passwords inside the payload.
Signature
The signature ensures that the token has not been modified.
It is generated using:
- Header
- Payload
- Secret Key
Add Required Dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.12.6</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <scope>runtime</scope> </dependency>
Configure Spring Security
Example 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(); }
Generate JWT Token
After successful login:
Username + Password ↓ Authentication ↓ Generate JWT ↓ Return Token
Example response:
{ "token":"eyJhbGciOiJIUzI1NiJ9..." }
Sending JWT in Requests
Clients include the token in the Authorization header.
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Every protected request should include this header.
Validate the Token
The server checks:
- Signature
- Expiration
- Username
- Claims
If the token is valid, access is granted.
JWT vs Session Authentication
| JWT | Session Authentication |
|---|---|
| Stateless | Stateful |
| Better for REST APIs | Better for traditional web apps |
| Scalable | Server stores sessions |
| Mobile-friendly | Browser-focused |
Token Expiration
JWT tokens should expire after a reasonable time.
Example:
Access Token: 15 minutes Refresh Token: 7 days
Short-lived access tokens reduce the impact of token theft.
Refresh Tokens
Instead of forcing users to log in repeatedly, applications often issue refresh tokens.
Flow:
Login ↓ Access Token + Refresh Token ↓ Access Token Expires ↓ Send Refresh Token ↓ Receive New Access Token
Best Practices
Always Use HTTPS
Transmit tokens only over encrypted connections.
Use Strong Secret Keys
Store secrets securely and avoid committing them to source control.
Keep Tokens Short-Lived
Use expiration times appropriate for your application.
Never Store Passwords in JWT
JWT payloads can be decoded, so avoid sensitive information.
Validate Every Request
Check the token on each protected endpoint.
Common Mistakes
Storing Sensitive Data
Do not include passwords or personal information in JWT payloads.
Ignoring Expiration
Expired tokens should always be rejected.
Using Weak Secret Keys
Choose long, random secret keys.
Forgetting HTTPS
Never send JWT tokens over unsecured HTTP.
Interview Questions
What is JWT?
JWT is a compact, signed token used for stateless authentication.
What are the three parts of JWT?
Header, Payload, and Signature.
Why is JWT suitable for REST APIs?
Because it is stateless and scales well across distributed systems.
What is the Authorization header format?
Authorization: Bearer <token>
FAQ
Is JWT encrypted?
No. JWT is signed by default, not encrypted. Anyone can decode the header and payload, but they cannot modify a valid token without the signing key.
Can JWT be revoked?
JWTs are not easily revoked. Many applications use short expiration times and refresh tokens to manage access.
Is JWT required for Spring Security?
No. Spring Security supports multiple authentication methods, including sessions, OAuth2, and JWT.
