Skip to the workspace
Pebellslearn by building
Spring Security  ›  Lesson

Authentication — Who Are You?

Authentication 14 minSpring Security's filter chain checks credentials before any controller runs, using a UserDetailsService and a PasswordEncoder, and stores the result in the SecurityContext.

spring boot / Authentication — Who Are You?

Explore each scene at your own pace.

01 · The rule

The rule

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 UserDetailsService loads a user by username (from the members table, say) and returns their stored password hash and roles.
  • A PasswordEncoder compares 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.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.