Spring Security — JWT Authentication
Implement JWT authentication with Spring Security: token generation, validation, and filter chain.
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;
@Component
public class JwtService {
private final SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
private final long expiration = 86400000; // 24 hours
public String generateToken(UserDetails user) {
return Jwts.builder()
.setSubject(user.getUsername())
.addClaims(Map.of("roles", user.getAuthorities()))
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(key)
.compact();
}
public String extractUsername(String token) {
return parseClaims(token).getSubject();
}
public boolean isValid(String token, UserDetails user) {
String username = extractUsername(token);
return username.equals(user.getUsername()) && !isExpired(token);
}
private boolean isExpired(String token) {
return parseClaims(token).getExpiration().before(new Date());
}
private Claims parseClaims(String token) {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
}
}
// Filter — add to SecurityFilterChain
// @Component
// public class JwtAuthFilter extends OncePerRequestFilter {
// protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
// String header = req.getHeader("Authorization");
// if (header != null && header.startsWith("Bearer ")) {
// String token = header.substring(7);
// String username = jwtService.extractUsername(token);
// // ... validate and set authentication context
// }
// chain.doFilter(req, res);
// }
// }Use Cases
- Securing REST APIs with JWT tokens
- Stateless authentication for microservices
- Token-based auth with Spring Security
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Spring Security — Role-Based Access Control
Configure RBAC with Spring Security: roles, method security, endpoint permissions, and custom filters.
Best for: Fine-grained API endpoint authorization
Spring Boot REST Controller with CRUD
Create a complete REST API with Spring Boot: GET, POST, PUT, DELETE with validation and error handling.
Best for: Building RESTful APIs with Spring Boot
Spring Boot Global Exception Handler
Centralized error handling with @ControllerAdvice for validation errors, 404s, and custom exceptions.
Best for: Consistent error responses across all endpoints
Spring Boot — Custom Validator Annotation
Create custom validation annotations with ConstraintValidator for domain-specific field validation.
Best for: Domain-specific input validation