Chapter 10

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.

⏱ 24 min readLevel: intermediate → advancedSpring Security 6

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).

Security filter chain: CORS and CSRF, authentication filter, SecurityContext, authorization, then the application — with 401 and 403 rejection paths
Filters run first. That is why a 401 never reaches your @RestControllerAdvice.
Adding the starter secures everything, immediately

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

StatusMeansClient should
401 Unauthorized"I do not know who you are" — missing or invalid credentialsAuthenticate 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.

security/SecurityConfig.java
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);
    }
}
Rule order is everything

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

MechanismGood forNotes
HTTP BasicInternal tools, service-to-service over mTLSCredentials on every request; HTTPS mandatory
Form login + sessionServer-rendered applicationsCSRF protection required
JWT resource serverSPAs and mobile clients with an external IdPThe default choice for a modern API
Opaque token introspectionWhen you need instant revocationA network call per request — cache it
OAuth2 clientCalling other services on a user's behalfspring-boot-starter-oauth2-client
API keysMachine clients, partner integrationsCustom 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.

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
application.yml
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
mapping token claims to Spring authorities
@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 vs hasAuthority

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

security/DatabaseUserDetailsService.java
@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();
    }
}
Password storage rules

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.

enabling and using it
@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) { }
}
@PostFilter loads everything first

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

three ways
// 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 applicationCSRF protectionWhy
Stateless API with bearer tokensDisableThe browser does not attach an Authorization header automatically, so the attack does not apply
Session cookies + browser clientsKeep it onCookies are attached automatically — this is exactly the attack
JWT stored in a cookieKeep it onYou reintroduced the cookie problem
cookie-based tokens for an SPA
.csrf(csrf -> csrf
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()))

CORS with security enabled

security/SecurityConfig.java
@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;
}
allowCredentials(true) plus "*" is rejected

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

security/ProblemAuthenticationEntryPoint.java
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

BookControllerSecurityTest.java
@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=framework behind 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.