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.
The shortcut
When a request is rejected, ask "Did the chain know who this was?"
- It did not (no credentials, or wrong ones): 401 Unauthorized, an authentication failure.
- It did, but the user is not allowed: 403 Forbidden. That is authorization, the next lesson.
Request arrives
POST /books/42/borrowwith anAuthorization: Basic ...header.
If the password had been wrong, the chain would stop the request with 401, and BookController would never run.
Drills
Answer fast — trust the rule.
Where does Spring Security check credentials?
A request arrives with no credentials for a protected endpoint. Which status is typical?
How should member passwords be stored?
After successful authentication, where does Spring Security keep the caller's identity for the rest of the request?
Remember
- Authentication proves who you are; the filter chain checks it before your code runs.
- Ask "did the chain know who this was?" No gives 401; yes-but-not-allowed gives 403.
- Trap: storing plain passwords — always go through a
PasswordEncoder.
