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)
sequenceDiagram
actor U as Athlete
participant D as DelegatingFilterProxy
participant F as FilterChainProxy
participant B as BasicAuthenticationFilter
participant M as ProviderManager
participant P as DaoAuthenticationProvider
participant S as UserDetailsService
participant E as PasswordEncoder
participant H as SecurityContextHolder
U->>D: GET /api/me (Authorization: Basic …)
D->>F: delegate to bean springSecurityFilterChain
F->>B: SecurityFilterChain for /api/**
B->>M: authenticate(UsernamePasswordAuthenticationToken)
M->>P: supports(token)? authenticate
P->>S: loadUserByUsername("marta")
S-->>P: UserDetails (hash, ROLE_COACH)
P->>E: matches(raw, hash)
alt valid
P-->>B: authenticated Authentication (credentials erased)
B->>H: setAuthentication()
B->>B: continue chain → AuthorizationFilter → DispatcherServlet
else invalid
P-->>B: BadCredentialsException → 401
endKey pieces
DelegatingFilterProxy→FilterChainProxy(beanspringSecurityFilterChain) →SecurityFilterChain(one or more)SecurityFilterChainas a@Beanconfigured withHttpSecurityAuthenticationManager→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 authorityROLE_COACHSecurityContextHolderuses aThreadLocalby default: theAuthenticationbelongs 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
userwith a password generated in the log
Exam traps
- Never store plain-text passwords:
NoOpPasswordEncoderis for tests only - The same text encoded twice with BCrypt gives different hashes (random salt): compare with
matches(), notequals() loadUserByUsernamemust throwUsernameNotFoundException, not returnnullWebSecurityConfigurerAdapterno longer exists (removed in Spring Security 6): you declareSecurityFilterChainbeans@WithMockUserskips authentication: it doesn't test yourUserDetailsServiceor your passwords