Spring Boot Security Review
Use when adding auth, handling input, creating endpoints, or dealing with secrets.
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
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith("Bearer ")) {
String token = header.substring(7);
Authentication auth = jwtService.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(request, response);
}
}
Authorization
- Enable method security:
@EnableMethodSecurity
- Use
@PreAuthorize("hasRole('ADMIN')") or @PreAuthorize("@authz.canEdit(#id)")
- Deny by default; expose only required scopes
Input Validation
- Use Bean Validation with
@Valid on controllers
- Apply constraints on DTOs:
@NotBlank, @Email, @Size, custom validators
- Sanitize any HTML with a whitelist before rendering
SQL Injection Prevention
- Use Spring Data repositories or parameterized queries
- For native queries, use
:param bindings; never concatenate strings
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
http
.csrf(csrf -> csrf.disable())
.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
Security Headers
http
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'"))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
.xssProtection(Customizer.withDefaults())
.referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));
Rate Limiting
- Apply Bucket4j or gateway-level limits on expensive endpoints
- Log and alert on bursts; return 429 with retry hints
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.
1---2name: springboot-security3description: Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.4---56# Spring Boot Security Review78Use when adding auth, handling input, creating endpoints, or dealing with secrets.910## Authentication1112- Prefer stateless JWT or opaque tokens with revocation list13- Use `httpOnly`, `Secure`, `SameSite=Strict` cookies for sessions14- Validate tokens with `OncePerRequestFilter` or resource server1516```java17@Component18public class JwtAuthFilter extends OncePerRequestFilter {19 private final JwtService jwtService;2021 public JwtAuthFilter(JwtService jwtService) {22 this.jwtService = jwtService;23 }2425 @Override26 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,27 FilterChain chain) throws ServletException, IOException {28 String header = request.getHeader(HttpHeaders.AUTHORIZATION);29 if (header != null && header.startsWith("Bearer ")) {30 String token = header.substring(7);31 Authentication auth = jwtService.authenticate(token);32 SecurityContextHolder.getContext().setAuthentication(auth);33 }34 chain.doFilter(request, response);35 }36}37```3839## Authorization4041- Enable method security: `@EnableMethodSecurity`42- Use `@PreAuthorize("hasRole('ADMIN')")` or `@PreAuthorize("@authz.canEdit(#id)")`43- Deny by default; expose only required scopes4445## Input Validation4647- Use Bean Validation with `@Valid` on controllers48- Apply constraints on DTOs: `@NotBlank`, `@Email`, `@Size`, custom validators49- Sanitize any HTML with a whitelist before rendering5051## SQL Injection Prevention5253- Use Spring Data repositories or parameterized queries54- For native queries, use `:param` bindings; never concatenate strings5556## CSRF Protection5758- For browser session apps, keep CSRF enabled; include token in forms/headers59- For pure APIs with Bearer tokens, disable CSRF and rely on stateless auth6061```java62http63 .csrf(csrf -> csrf.disable())64 .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));65```6667## Secrets Management6869- No secrets in source; load from env or vault70- Keep `application.yml` free of credentials; use placeholders71- Rotate tokens and DB credentials regularly7273## Security Headers7475```java76http77 .headers(headers -> headers78 .contentSecurityPolicy(csp -> csp79 .policyDirectives("default-src 'self'"))80 .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)81 .xssProtection(Customizer.withDefaults())82 .referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));83```8485## Rate Limiting8687- Apply Bucket4j or gateway-level limits on expensive endpoints88- Log and alert on bursts; return 429 with retry hints8990## Dependency Security9192- Run OWASP Dependency Check / Snyk in CI93- Keep Spring Boot and Spring Security on supported versions94- Fail builds on known CVEs9596## Logging and PII9798- Never log secrets, tokens, passwords, or full PAN data99- Redact sensitive fields; use structured JSON logging100101## File Uploads102103- Validate size, content type, and extension104- Store outside web root; scan if required105106## Checklist Before Release107108- [ ] Auth tokens validated and expired correctly109- [ ] Authorization guards on every sensitive path110- [ ] All inputs validated and sanitized111- [ ] No string-concatenated SQL112- [ ] CSRF posture correct for app type113- [ ] Secrets externalized; none committed114- [ ] Security headers configured115- [ ] Rate limiting on APIs116- [ ] Dependencies scanned and up to date117- [ ] Logs free of sensitive data118119**Remember**: Deny by default, validate inputs, least privilege, and secure-by-configuration first.