Authentication — Who Are You?
The moment you add spring-boot-starter-security to library-service, every endpoint starts answering 401 Unauthorized, and a line appears in the log: Using generated security password: 3f9c.... Nothing is broken. Spring Security has locked every door and is waiting for you to say who may come in and how they prove it.
The rule
Authentication proves who you are; the filter chain checks it before your code runs.
Spring Security works as a chain of servlet filters that sits in front of the DispatcherServlet. Each request passes through the chain before any controller sees it. One of those filters tries to authenticate the request: read the credentials, check them, and on success store an Authentication object in the SecurityContext. From then on, the rest of the request knows who the caller is.
Out of the box you get one user named user with that generated password, and both a login form and HTTP Basic are switched on. Real apps replace this with their own setup:
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/books/**").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}Two more pieces complete the picture:
- A
UserDetailsServiceloads a user by username (from the members table, say) and returns their stored password hash and roles. - A
PasswordEncodercompares the typed password with the stored hash. Passwords are never stored as plain text. The delegating encoder above uses bcrypt by default and prefixes each hash with{bcrypt}so the algorithm can change later.