Security
Spring Security has a reputation for being impenetrable. Most of that comes from tutorials written for a config style that was removed in version 6. Here is the current one, and the mental model that makes it click.
The mental model
Spring Security is a chain of servlet filters that runs before Spring MVC. It has no idea your controllers exist. It sees a request, decides who is making it (authentication) and whether they may proceed (authorization).
Put spring-boot-starter-security on the classpath with no configuration and
every endpoint requires HTTP Basic authentication as user user, with a random
password printed at startup. That is deliberate — insecure-by-default would be worse. The
fix is to configure it, never to exclude the auto-configuration.
The 401 vs 403 distinction
| Status | Means | Client should |
|---|---|---|
| 401 Unauthorized | "I do not know who you are" — missing or invalid credentials | Authenticate and retry |
| 403 Forbidden | "I know who you are, and you may not do this" | Not retry; this will never succeed |
The SecurityFilterChain bean
In Spring Security 6, WebSecurityConfigurerAdapter is gone. You define a
SecurityFilterChain bean using the lambda DSL. Every tutorial using
extends WebSecurityConfigurerAdapter or .authorizeRequests() is
out of date.
package com.bitsnippets.bookstore.security;
import org.springframework.context.annotation.*;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
return http
/* stateless JSON API: no sessions, no CSRF token to protect */
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.cors(Customizer.withDefaults())
/* rules are evaluated TOP TO BOTTOM — first match wins */
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health/**", "/actuator/info").permitAll()
.requestMatchers(HttpMethod.GET, "/api/books/**").permitAll()
.requestMatchers(HttpMethod.POST, "/api/books/**").hasRole("EDITOR")
.requestMatchers(HttpMethod.PUT, "/api/books/**").hasRole("EDITOR")
.requestMatchers(HttpMethod.DELETE, "/api/books/**").hasRole("ADMIN")
.requestMatchers("/actuator/**").hasRole("ADMIN")
.anyRequest().authenticated()) // ← always LAST
/* JWT bearer tokens issued by an external identity provider */
.oauth2ResourceServer(oauth -> oauth
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthConverter())))
/* return JSON, not an HTML login page */
.exceptionHandling(ex -> ex
.authenticationEntryPoint(new ProblemAuthenticationEntryPoint())
.accessDeniedHandler(new ProblemAccessDeniedHandler()))
.headers(headers -> headers
.frameOptions(frame -> frame.deny())
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31_536_000)))
.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
Matchers are evaluated in declaration order and the first match wins. Put
anyRequest() first and every rule below it is dead code — with no warning.
Equally, a broad requestMatchers("/api/**").permitAll() placed above a
specific rule silently opens the specific endpoint.
Authentication options
| Mechanism | Good for | Notes |
|---|---|---|
| HTTP Basic | Internal tools, service-to-service over mTLS | Credentials on every request; HTTPS mandatory |
| Form login + session | Server-rendered applications | CSRF protection required |
| JWT resource server | SPAs and mobile clients with an external IdP | The default choice for a modern API |
| Opaque token introspection | When you need instant revocation | A network call per request — cache it |
| OAuth2 client | Calling other services on a user's behalf | spring-boot-starter-oauth2-client |
| API keys | Machine clients, partner integrations | Custom filter; hash the keys at rest |
JWT resource server — the common case
Do not write your own JWT parsing filter. Boot has one, it validates signature, expiry, issuer and audience, and it rotates signing keys automatically.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
spring:
security:
oauth2:
resourceserver:
jwt:
# keys are fetched and cached from the provider's JWKS endpoint
issuer-uri: https://auth.example.com/realms/bookstore
audiences: bookstore-api
@Bean
JwtAuthenticationConverter jwtAuthConverter() {
JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter();
authorities.setAuthoritiesClaimName("roles"); // your IdP's claim name
authorities.setAuthorityPrefix("ROLE_"); // hasRole("ADMIN") needs ROLE_ADMIN
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authorities);
converter.setPrincipalClaimName("preferred_username");
return converter;
}
hasRole("ADMIN") checks for the authority ROLE_ADMIN — it adds
the prefix for you. hasAuthority("ADMIN") checks for exactly
ADMIN. Mixing the two, or forgetting the prefix in your claims converter, is
the most common cause of an unexplained 403.
Database-backed users
@Service
public class DatabaseUserDetailsService implements UserDetailsService {
private final AppUserRepository users;
public DatabaseUserDetailsService(AppUserRepository users) {
this.users = users;
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
AppUser user = users.findByUsernameWithRoles(username)
.orElseThrow(() -> new UsernameNotFoundException("No such user"));
return User.withUsername(user.getUsername())
.password(user.getPasswordHash())
.authorities(user.getRoles().stream()
.map(r -> new SimpleGrantedAuthority("ROLE_" + r.getName()))
.toList())
.accountLocked(user.isLocked())
.disabled(!user.isEnabled())
.build();
}
}
Store a hash, never the password, and never anything reversible. Use BCrypt (cost 12+), Argon2 or SCrypt — never MD5, SHA-1 or plain SHA-256, which are far too fast to be safe. Never log a password, even at DEBUG. And do not reveal in the error whether the username or the password was wrong: both must produce the same generic failure, or you have built a user-enumeration endpoint.
Method security
URL rules cannot express "the owner, or an admin". Method security can, and it protects the service even if a new controller forgets a rule.
@Configuration
@EnableMethodSecurity // prePostEnabled is true by default
public class MethodSecurityConfig { }
@Service
public class ReviewService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteAny(Long reviewId) { }
/* the owner or an admin */
@PreAuthorize("hasRole('ADMIN') or #review.authorName == authentication.name")
public void update(Review review) { }
/* check the RESULT, after the method runs */
@PostAuthorize("returnObject.authorName == authentication.name or hasRole('ADMIN')")
public Review find(Long id) { }
/* filter a collection down to what the caller may see */
@PostFilter("filterObject.published or filterObject.authorName == authentication.name")
public List<Review> findAllForBook(Long bookId) { }
}
It fetches the full result set and then discards rows in memory. On anything larger than a
page, filter in the query instead. The same applies to @PostAuthorize — the
method has already run, including its side effects.
Reading the current user
// 1 · inject it as a method argument — cleanest
@GetMapping("/me")
public ProfileResponse me(@AuthenticationPrincipal Jwt jwt) {
return profileService.forSubject(jwt.getSubject());
}
// 2 · from the security context, anywhere
String username = SecurityContextHolder.getContext().getAuthentication().getName();
// 3 · a custom annotation for readability
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal(expression = "claims['preferred_username']")
public @interface CurrentUsername { }
@GetMapping("/orders")
public List<OrderResponse> myOrders(@CurrentUsername String username) { }
CSRF, honestly
| Your application | CSRF protection | Why |
|---|---|---|
| Stateless API with bearer tokens | Disable | The browser does not attach an Authorization header automatically, so the attack does not apply |
| Session cookies + browser clients | Keep it on | Cookies are attached automatically — this is exactly the attack |
| JWT stored in a cookie | Keep it on | You reintroduced the cookie problem |
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()))
CORS with security enabled
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://bookstore.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setExposedHeaders(List.of("Location"));
config.setAllowCredentials(true);
config.setMaxAge(Duration.ofHours(1));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
The browser refuses that combination — it would let any site read authenticated responses.
List real origins. If your CORS worked before you added the security starter and broke
afterwards, it is because the security filter chain now handles preflight requests and
needs its own .cors(...) configuration, as above.
JSON errors instead of HTML
public class ProblemAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.UNAUTHORIZED, "Authentication is required");
problem.setTitle("Unauthorized");
problem.setInstance(URI.create(request.getRequestURI()));
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/problem+json");
mapper.writeValue(response.getOutputStream(), problem);
}
}
Testing secured endpoints
@WebMvcTest(BookController.class)
@Import(SecurityConfig.class) // slices do not load it automatically
class BookControllerSecurityTest {
@Autowired MockMvc mvc;
@MockitoBean BookService bookService;
@Test
void anonymousCanRead() throws Exception {
mvc.perform(get("/api/books/1")).andExpect(status().isOk());
}
@Test
void anonymousCannotCreate() throws Exception {
mvc.perform(post("/api/books").contentType(APPLICATION_JSON).content("{}"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "USER")
void plainUserCannotCreate() throws Exception {
mvc.perform(post("/api/books").contentType(APPLICATION_JSON).content("{}"))
.andExpect(status().isForbidden());
}
@Test
void editorCanCreate() throws Exception {
mvc.perform(post("/api/books")
.with(jwt().authorities(new SimpleGrantedAuthority("ROLE_EDITOR")))
.contentType(APPLICATION_JSON)
.content(validBookJson()))
.andExpect(status().isCreated());
}
}
Add spring-security-test as a test dependency for @WithMockUser,
jwt() and the other request post-processors.
Production baseline
- HTTPS everywhere; HSTS enabled;
server.forward-headers-strategy=frameworkbehind a proxy. anyRequest().authenticated()is the last rule — deny by default.- Passwords hashed with BCrypt 12+ or Argon2; identical error for unknown user and wrong password.
- Rate limiting on login and token endpoints.
- Actuator on a separate port or behind
hasRole("ADMIN"). - No secrets in the repository; rotate on exposure.
- Security tests for anonymous, wrong-role and correct-role on every protected route.
- Dependency scanning in CI — most real breaches come from an unpatched library, not your code.
Your rules list anyRequest().authenticated() first, then
requestMatchers("/public/**").permitAll(). What happens?
Matchers are evaluated top to bottom and the first match decides.
anyRequest() matches everything, so nothing after it is ever reached. It must
always be the final rule.