Spring Boot Security Review
Use when adding auth, handling input, creating endpoints, or dealing with secrets.
When to Activate
- Adding authentication (JWT, OAuth2, session-based)
- Implementing authorization (@PreAuthorize, role-based access)
- Validating user input (Bean Validation, custom validators)
- Configuring CORS, CSRF, or security headers
- Managing secrets (Vault, environment variables)
- Adding rate limiting or brute-force protection
- Scanning dependencies for CVEs
Authentication
- Prefer stateless JWT or opaque tokens with revocation list
- Use
httpOnly, Secure, SameSite=Strict cookies for sessions
- Validate tokens with
OncePerRequestFilter or resource server
java
1@Component
2public class JwtAuthFilter extends OncePerRequestFilter {
3 private final JwtService jwtService;
4
5 public JwtAuthFilter(JwtService jwtService) {
6 this.jwtService = jwtService;
7 }
8
9 @Override
10 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
11 FilterChain chain) throws ServletException, IOException {
12 String header = request.getHeader(HttpHeaders.AUTHORIZATION);
13 if (header != null && header.startsWith("Bearer ")) {
14 String token = header.substring(7);
15 Authentication auth = jwtService.authenticate(token);
16 SecurityContextHolder.getContext().setAuthentication(auth);
17 }
18 chain.doFilter(request, response);
19 }
20}
Authorization
- Enable method security:
@EnableMethodSecurity
- Use
@PreAuthorize("hasRole('ADMIN')") or @PreAuthorize("@authz.canEdit(#id)")
- Deny by default; expose only required scopes
java
1@RestController
2@RequestMapping("/api/admin")
3public class AdminController {
4
5 @PreAuthorize("hasRole('ADMIN')")
6 @GetMapping("/users")
7 public List<UserDto> listUsers() {
8 return userService.findAll();
9 }
10
11 @PreAuthorize("@authz.isOwner(#id, authentication)")
12 @DeleteMapping("/users/{id}")
13 public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
14 userService.delete(id);
15 return ResponseEntity.noContent().build();
16 }
17}
- Use Bean Validation with
@Valid on controllers
- Apply constraints on DTOs:
@NotBlank, @Email, @Size, custom validators
- Sanitize any HTML with a whitelist before rendering
java
1// BAD: No validation
2@PostMapping("/users")
3public User createUser(@RequestBody UserDto dto) {
4 return userService.create(dto);
5}
6
7// GOOD: Validated DTO
8public record CreateUserDto(
9 @NotBlank @Size(max = 100) String name,
10 @NotBlank @Email String email,
11 @NotNull @Min(0) @Max(150) Integer age
12) {}
13
14@PostMapping("/users")
15public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
16 return ResponseEntity.status(HttpStatus.CREATED)
17 .body(userService.create(dto));
18}
SQL Injection Prevention
- Use Spring Data repositories or parameterized queries
- For native queries, use
:param bindings; never concatenate strings
java
1// BAD: String concatenation in native query
2@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
3
4// GOOD: Parameterized native query
5@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
6List<User> findByName(@Param("name") String name);
7
8// GOOD: Spring Data derived query (auto-parameterized)
9List<User> findByEmailAndActiveTrue(String email);
Password Encoding
- Always hash passwords with BCrypt or Argon2 — never store plaintext
- Use
PasswordEncoder bean, not manual hashing
java
1@Bean
2public PasswordEncoder passwordEncoder() {
3 return new BCryptPasswordEncoder(12); // cost factor 12
4}
5
6// In service
7public User register(CreateUserDto dto) {
8 String hashedPassword = passwordEncoder.encode(dto.password());
9 return userRepository.save(new User(dto.email(), hashedPassword));
10}
CSRF Protection
- For browser session apps, keep CSRF enabled; include token in forms/headers
- For pure APIs with Bearer tokens, disable CSRF and rely on stateless auth
java
1http
2 .csrf(csrf -> csrf.disable())
3 .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
Secrets Management
- No secrets in source; load from env or vault
- Keep
application.yml free of credentials; use placeholders
- Rotate tokens and DB credentials regularly
yaml
1# BAD: Hardcoded in application.yml
2spring:
3 datasource:
4 password: mySecretPassword123
5
6# GOOD: Environment variable placeholder
7spring:
8 datasource:
9 password: ${DB_PASSWORD}
10
11# GOOD: Spring Cloud Vault integration
12spring:
13 cloud:
14 vault:
15 uri: https://vault.example.com
16 token: ${VAULT_TOKEN}
java
1http
2 .headers(headers -> headers
3 .contentSecurityPolicy(csp -> csp
4 .policyDirectives("default-src 'self'"))
5 .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
6 .xssProtection(Customizer.withDefaults())
7 .referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));
CORS Configuration
- Configure CORS at the security filter level, not per-controller
- Restrict allowed origins — never use
* in production
java
1@Bean
2public CorsConfigurationSource corsConfigurationSource() {
3 CorsConfiguration config = new CorsConfiguration();
4 config.setAllowedOrigins(List.of("https://app.example.com"));
5 config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
6 config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
7 config.setAllowCredentials(true);
8 config.setMaxAge(3600L);
9
10 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
11 source.registerCorsConfiguration("/api/**", config);
12 return source;
13}
14
15// In SecurityFilterChain:
16http.cors(cors -> cors.configurationSource(corsConfigurationSource()));
Rate Limiting
- Apply Bucket4j or gateway-level limits on expensive endpoints
- Log and alert on bursts; return 429 with retry hints
java
1// Using Bucket4j for per-endpoint rate limiting
2@Component
3public class RateLimitFilter extends OncePerRequestFilter {
4 private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
5
6 private Bucket createBucket() {
7 return Bucket.builder()
8 .addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1))))
9 .build();
10 }
11
12 @Override
13 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
14 FilterChain chain) throws ServletException, IOException {
15 String clientIp = request.getRemoteAddr();
16 Bucket bucket = buckets.computeIfAbsent(clientIp, k -> createBucket());
17
18 if (bucket.tryConsume(1)) {
19 chain.doFilter(request, response);
20 } else {
21 response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
22 response.getWriter().write("{\"error\": \"Rate limit exceeded\"}");
23 }
24 }
25}
Dependency Security
- Run OWASP Dependency Check / Snyk in CI
- Keep Spring Boot and Spring Security on supported versions
- Fail builds on known CVEs
Logging and PII
- Never log secrets, tokens, passwords, or full PAN data
- Redact sensitive fields; use structured JSON logging
File Uploads
- Validate size, content type, and extension
- Store outside web root; scan if required
Checklist Before Release
Remember: Deny by default, validate inputs, least privilege, and secure-by-configuration first.