Cheatsheet

Spring Security: architecture and authentication

Key idea

Spring Security protects a web application with a chain of servlet filters that runs before your controllers. An authentication filter extracts the credentials and passes them to the `AuthenticationManager`, which validates them with an `AuthenticationProvider` (users from a `UserDetailsService`, passwords with a `PasswordEncoder`). The result, an `Authentication`, is stored in the thread's `SecurityContextHolder`.

Diagram (UML)

ApplicationContextAthleteDelegatingFilterProxyFilterChainProxySecurityFilterChainBoxControllerProviderManagerSecurityContextHolderDaoAuthenticationProviderUserDetailsServicePasswordEncoder

Key pieces

  • DelegatingFilterProxy → FilterChainProxy (bean springSecurityFilterChain) → SecurityFilterChain (one or more)
  • SecurityFilterChain as a @Bean configured with HttpSecurity
  • AuthenticationManager → ProviderManager → AuthenticationProvider (DaoAuthenticationProvider)
  • UserDetailsService.loadUserByUsername(), UserDetails, User.withUsername(...).roles(...)
  • PasswordEncoder: BCryptPasswordEncoder, DelegatingPasswordEncoder ({bcrypt}…)
  • SecurityContextHolder → SecurityContext → Authentication (principal, credentials, authorities)

SecurityConfig.java

@Bean
public SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/public/**").permitAll()   // the timetable is public
            .anyRequest().authenticated())                   // everything else needs a login
        .httpBasic(withDefaults())                           // Authorization: Basic …
        .csrf(csrf -> csrf.disable());                       // stateless API (see the next lesson)
    return http.build();
}

Remember for the exam

  • Authentication: who you are. Authorization: what you may do
  • Not authenticated → 401 Unauthorized; authenticated but not allowed → 403 Forbidden
  • Security filters act before the DispatcherServlet
  • roles("COACH") creates the authority ROLE_COACH
  • SecurityContextHolder uses a ThreadLocal by default: the Authentication belongs to the request thread
  • After authenticating, credentials are erased from the Authentication (eraseCredentials)
  • Spring Boot with no configuration: everything protected, form login and HTTP Basic, and a user with a password generated in the log

Exam traps

  • Never store plain-text passwords: NoOpPasswordEncoder is for tests only
  • The same text encoded twice with BCrypt gives different hashes (random salt): compare with matches(), not equals()
  • loadUserByUsername must throw UsernameNotFoundException, not return null
  • WebSecurityConfigurerAdapter no longer exists (removed in Spring Security 6): you declare SecurityFilterChain beans
  • @WithMockUser skips authentication: it doesn't test your UserDetailsService or your passwords

← Spring Security: architecture and authentication · Run it