Spring Boot

Article 14: JWT Authentication in Spring Boot

By Utility Zone · 2026-01-27T18:29:24.786818

1. Introduction

Basic authentication is fine for demos, but real-world applications use token-based security.

JWT (JSON Web Token) allows:

  • Stateless authentication
  • Scalable microservices
  • Secure client–server communication

This article introduces JWT authentication step by step.


2. What Is JWT?

JWT is a compact token that contains:

  • Header (algorithm info)
  • Payload (user data / claims)
  • Signature (verification)

Format:

xxxxx.yyyyy.zzzzz

JWT is: ✔ Stateless
✔ Self-contained
✔ Widely used


3. How JWT Authentication Works

Flow:

  1. User logs in with username & password
  2. Server validates credentials
  3. Server generates JWT
  4. Client sends JWT in Authorization header
  5. Server validates JWT for every request

No session storage on server.


4. Adding JWT Dependencies

Add to pom.xml:

<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>

5. Creating JWT Utility Class

@Component
public class JwtUtil {

    private final String SECRET_KEY = "my-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();
    }

    public String extractUsername(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY.getBytes())
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }
}

6. Creating Login API

@PostMapping("/login")
public String login(@RequestBody LoginRequest request) {
    authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(
            request.getUsername(), request.getPassword())
    );

    return jwtUtil.generateToken(request.getUsername());
}

Returns JWT on success.


7. JWT Authentication Filter

JWT must be validated for every request.

public class JwtFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        String header = request.getHeader("Authorization");

        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            String username = jwtUtil.extractUsername(token);

            UsernamePasswordAuthenticationToken auth =
                    new UsernamePasswordAuthenticationToken(username, null, List.of());

            SecurityContextHolder.getContext().setAuthentication(auth);
        }

        filterChain.doFilter(request, response);
    }
}

8. Updating Security Configuration

http
    .csrf(csrf -> csrf.disable())
    .authorizeHttpRequests(auth -> auth
        .requestMatchers("/login").permitAll()
        .anyRequest().authenticated()
    )
    .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);

9. Testing JWT Flow

  1. Call /login → receive token
  2. Call protected API with header:
Authorization: Bearer <token>
  1. Access granted

10. Common JWT Mistakes

❌ Hardcoding secret in code
❌ Long token expiry
❌ Not validating signature
❌ Storing JWT in localStorage blindly


11. Best Practices

✔ Store secret in environment variables
✔ Use short expiry + refresh tokens
✔ Always validate token
✔ Use HTTPS


12. What You Should Understand Before Moving On

You should now know:

  • How JWT works
  • How login generates token
  • How token is validated
  • Why JWT is stateless

13. What’s Next?

➡ Article 15: Logging & Monitoring

  • SLF4J & Logback
  • Spring Boot Actuator
  • Health & metrics

Type Next when you’re ready.