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:

  1. User logs in
  2. Server validates credentials
  3. JWT token is generated
  4. Client stores token
  5. Token sent in Authorization header
  6. API validates token
  7. Access granted to protected resources

Technologies Used

TechnologyPurpose
Spring BootBackend framework
Spring SecurityAuthentication & authorization
JWTToken-based security
MavenDependency management
PostgreSQL/MySQLDatabase
BCryptPassword 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

IssueSolution
Invalid tokenVerify secret key
Expired tokenImplement refresh tokens
Unauthorized accessValidate roles correctly
Weak passwordsUse BCrypt hashing
CORS issuesConfigure CORS properly

Recommended Architecture for Enterprises

LayerTechnology
BackendSpring Boot
SecuritySpring Security
AuthenticationJWT
API GatewayKong / NGINX
Identity ProviderKeycloak
DatabasePostgreSQL
MonitoringPrometheus + 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


📢 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

Popular posts from this blog

Top 50 Camunda BPM Interview Questions and Answers for Developers (2026 Guide)

OOPs Concepts in Java | English | Object Oriented Programming Explained

Scopes of Signal in jBPM