spring-boot-security
Spring Boot security
This skill covers securing one service's own endpoints. For service-to-service authentication/authorization in a multi-service system (propagating an identity/JWT to a downstream call, mTLS between services, an API gateway's auth responsibilities), see spring-boot-microservices.
Authentication
Prefer stateless JWT (or an opaque token with a server-side revocation list) over session-based auth for REST APIs. See spring-boot-core's stateless security config example for the base SecurityFilterChain shape (STATELESS session policy, CSRF disabled, lambda DSL).
- Passwords:
BCryptPasswordEncoder, cost factor 12 as a floor for new applications — the default cost factor in older examples (10) is now considered too fast to resist offline brute-forcing on modern hardware. - Never store or log raw tokens; if persisting tokens for revocation/logout tracking, store only a SHA-256 hash of the token, not the raw value.
Authorization
Use @EnableMethodSecurity + @PreAuthorize with SpEL expressions over @Secured — @Secured only does a simple role-string match, @PreAuthorize can check multiple roles, inspect method arguments, and combine conditions. Deny by default: anyRequest().authenticated() as the catch-all in the security filter chain, with specific permitAll() exceptions listed explicitly above it — never the reverse.
Input validation
@Valid on every controller method accepting a request body, with Jakarta Bean Validation constraints on the DTO (@NotBlank, @Email, @Size) — see spring-boot-scaffold for the nested/cascading @Valid gotcha. Validate at the boundary; don't rely on service-layer checks alone.