Build Secure Authentication System with Spring Boot & JWT | Complete Example
Modern enterprise applications require secure authentication and authorization mechanisms to protect APIs, user data, and business operations. Traditional session-based authentication often struggles in cloud-native and microservices environments.
Spring Boot with JWT (JSON Web Token) authentication provides a scalable, stateless, and production-ready security solution for modern Java applications.
This guide explains how to build a complete secure authentication system using Spring Boot, Spring Security, and JWT with real enterprise best practices.
Why Use JWT Authentication?
JWT authentication is widely used in:
- REST APIs
- Microservices
- Mobile applications
- Cloud-native systems
- Single Page Applications (SPA)
Benefits include:
- Stateless authentication
- Better scalability
- Secure API access
- Easy integration with microservices
- Reduced server session overhead
JWT Authentication Architecture
A typical JWT authentication flow:
- User logs in
- Server validates credentials
- JWT token is generated
- Client stores token
- Token sent in Authorization header
- API validates token
- Access granted to protected resources
Technologies Used
| Technology | Purpose |
|---|---|
| Spring Boot | Backend framework |
| Spring Security | Authentication & authorization |
| JWT | Token-based security |
| Maven | Dependency management |
| PostgreSQL/MySQL | Database |
| BCrypt | Password encryption |
Maven Dependencies
Add the following dependencies:
<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.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>
</dependencies>
User Entity Example
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;
}
Password Encryption with BCrypt
Never store plain-text passwords.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
BCrypt provides:
- Secure hashing
- Salt generation
- Brute-force resistance
JWT Utility Class
JWT utility for token creation and validation:
@Component
public class JwtUtil {
private final String SECRET_KEY = "secret-key";
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 Authentication Filter
The filter validates incoming JWT tokens.
@Component
public class JwtFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
String authHeader =
request.getHeader("Authorization");
if(authHeader != null &&
authHeader.startsWith("Bearer ")) {
String token =
authHeader.substring(7);
// Validate token here
}
chain.doFilter(request, response);
}
}
Spring Security Configuration
Configure secure API endpoints:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(
HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/**")
.permitAll()
.anyRequest()
.authenticated()
);
return http.build();
}
}
Authentication Controller
Login endpoint example:
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/login")
public String login(
@RequestBody LoginRequest request) {
// Validate user credentials
return jwtUtil.generateToken(
request.getUsername()
);
}
}
Example API Request
Login Request
{
"username":"admin",
"password":"password"
}
Response
{
"token":"eyJhbGciOiJIUzI1NiJ9..."
}
Securing REST APIs
Protected APIs require:
Authorization: Bearer JWT_TOKEN
This ensures only authenticated users can access business services.
Role-Based Authorization
Spring Security supports role-based access control.
Example:
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminApi() {
return "Admin Access";
}
Roles commonly used:
- ADMIN
- USER
- MANAGER
- SUPER_ADMIN
JWT Best Practices
Use HTTPS
Always secure APIs using SSL/TLS.
Set Token Expiration
Avoid long-lived JWT tokens.
Use Refresh Tokens
Improve user experience securely.
Encrypt Sensitive Data
Never expose confidential information inside JWT payloads.
Store Secrets Securely
Use Vault or environment variables instead of hardcoded secrets.
Production Security Recommendations
API Gateway Security
Use:
- Kong
- NGINX
- Spring Cloud Gateway
Centralized Authentication
Use OAuth2 providers like:
- Keycloak
- Okta
- Auth0
Enable Monitoring
Track:
- Failed login attempts
- Suspicious API activity
- Token misuse
Real Enterprise Use Case
A fintech company migrated from session-based authentication to JWT-based microservice security using Spring Boot.
Results achieved:
- Improved API scalability
- Faster authentication response time
- Reduced server memory usage
- Better cloud-native compatibility
- Centralized authentication management
Common JWT Authentication Errors
| Issue | Solution |
|---|---|
| Invalid token | Verify secret key |
| Expired token | Implement refresh tokens |
| Unauthorized access | Validate roles correctly |
| Weak passwords | Use BCrypt hashing |
| CORS issues | Configure CORS properly |
Recommended Architecture for Enterprises
| Layer | Technology |
|---|---|
| Backend | Spring Boot |
| Security | Spring Security |
| Authentication | JWT |
| API Gateway | Kong / NGINX |
| Identity Provider | Keycloak |
| Database | PostgreSQL |
| Monitoring | Prometheus + Grafana |
Final Thoughts
Building a secure authentication system using Spring Boot and JWT enables enterprises to create scalable, stateless, and cloud-ready applications.
By combining Spring Security, JWT token validation, password encryption, and role-based authorization, organizations can secure APIs effectively while maintaining high performance and flexibility.
JWT-based authentication remains one of the most important security implementations for modern Java microservices and enterprise applications.
Recommended Articles
- Java Production Readiness Checklist
- Microservices Architecture for Enterprises
- Workflow-Oriented Microservices (Camunda + Kafka)
- Alfresco REST API Tutorial
- Event-Driven Microservices (Kafka + Spring Boot)
📢 Need help with Java, workflows, or backend systems?
I help teams design scalable, high-performance, production-ready applications and solve critical real-world issues.
Services:
- Java & Spring Boot development
- Camunda Training / consulting
- Alfresco Training / consulting
- Workflow architecture guidance
- Workflow implementation (Camunda, Flowable – BPMN, DMN)
- Backend & API integrations (REST, microservices)
- Document management & ECM integrations (Alfresco)
- Performance optimization & production issue resolution
🔗 https://shikhanirankari.blogspot.com/p/professional-services.html
📩 Email: ishikhanirankari@gmail.com | info@realtechnologiesindia.com
🌐 https://realtechnologiesindia.com
✔ Available for quick consultations
✔ Response within 24 hours
Comments
Post a Comment