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`.
In the box
The box's coach area checked username and password by hand in every endpoint, with the password in plain text. See how a filter chain intercepts every request, how someone is authenticated with AuthenticationManager, UserDetailsService and PasswordEncoder, and where their identity is kept.
AthleteManualAuthController

The athlete sends the Authorization header straight to ManualAuthController, highlighted in red, which decodes and compares it by hand.

The GET /api/me request goes through the DelegatingFilterProxy, which delegates to the FilterChainProxy and that to the SecurityFilterChain; all three are highlighted.

The FilterChainProxy passes the request to the SecurityFilterChain, highlighted, whose configuration decides which paths are open and how authentication happens.

The SecurityFilterChain sends authenticate(token) to ProviderManager, which passes it to DaoAuthenticationProvider; both are highlighted.

DaoAuthenticationProvider asks the UserDetailsService, highlighted, for loadUserByUsername("marta").

DaoAuthenticationProvider sends matches(raw, hash) to the PasswordEncoder, highlighted.

The SecurityFilterChain stores the Authentication in the SecurityContextHolder, highlighted, and BoxController reads it with getAuthentication().

GET /api/me with Basic marta goes through the filter chain, highlighted, and reaches the controller with a 200; without credentials it stops at 401.

Final view: the filter chain on top, the authentication manager with its provider, the UserDetailsService and the PasswordEncoder below, and the SecurityContextHolder on the right.

Step 1 of 9

Passwords in every endpoint

The box's coach area started with ManualAuthController: each endpoint reads the Authorization header, decodes it from Base64, splits username and password and compares them… with a plain-text password written in the code.

  • It's repeated in every endpoint (and forgetting it in one is enough).
  • Passwords aren't protected.
  • It mixes security with box logic.

Step 2 of 9

A chain of filters in front of everything

Spring Security hooks into the application with servlet filters, which run before the DispatcherServlet:

  1. DelegatingFilterProxy: a filter registered in the container (Tomcat) that delegates to a Spring bean called springSecurityFilterChain. It's the bridge between the container, which doesn't know Spring, and the beans.
  2. FilterChainProxy: that bean. It picks which SecurityFilterChain applies to the request (there can be several, for instance one for /api/** and another for the web pages).
  3. The SecurityFilterChain: the ordered list of security filters. The test lists some of them: SecurityContextHolderFilter, BasicAuthenticationFilter, ExceptionTranslationFilter and AuthorizationFilter.

Step 3 of 9

Configuring the chain: a SecurityFilterChain bean

The chain is configured with a @Bean SecurityFilterChain built from HttpSecurity:

  • authorizeHttpRequests(...): /api/public/** is open (permitAll()) and the rest requires being authenticated.
  • httpBasic(withDefaults()): adds the HTTP Basic filter.
  • csrf(...): you'll see it in the next lesson.

Step 4 of 9

AuthenticationManager and its providers

The BasicAuthenticationFilter takes username and password from the header, puts them in a UsernamePasswordAuthenticationToken (still unauthenticated) and passes it to the AuthenticationManager:

  • The usual implementation is ProviderManager, which goes through a list of **AuthenticationProvider**s and uses the first one that supports that token type.
  • For username and password it's DaoAuthenticationProvider.
  • If everything checks out, it returns an authenticated Authentication, with authorities and without credentials (they're erased). Otherwise it throws BadCredentialsException.

Step 5 of 9

UserDetailsService: who is marta?

DaoAuthenticationProvider doesn't know where your users live. A UserDetailsService tells it, an interface with a single method:

UserDetails loadUserByUsername(String username)

MemberUserDetailsService keeps them in memory (in real life, in the database). Each UserDetails carries the name, the encoded password and the authorities: roles("COACH") creates the authority ROLE_COACH.

Step 6 of 9

PasswordEncoder: hashes, not passwords

The provider compares the received password with the stored one using a PasswordEncoder:

  • encode(raw) produces a salted hash; matches(raw, hash) checks it.
  • BCrypt puts a random salt in each hash: encoding the same text twice gives different hashes. That's why you compare with matches, never with equals.
  • DelegatingPasswordEncoder prefixes the algorithm: {bcrypt}$2a$…. That way you can migrate algorithms without breaking old passwords.

Step 7 of 9

SecurityContextHolder: who's here

With the user authenticated, the filter stores the Authentication in the SecurityContext, inside the SecurityContextHolder. By default it's a ThreadLocal: each request thread has its own.

From your code you read it three ways, and all three give the same object:

  • SecurityContextHolder.getContext().getAuthentication().
  • An Authentication (or Principal) parameter on the controller method.
  • @AuthenticationPrincipal UserDetails user for the principal itself.

Step 8 of 9

The full request

Putting it all together, the test covers four cases with MockMvc and httpBasic(...) from spring-security-test:

  • /api/public/timetable without credentials → 200 (permitAll).
  • /api/me without credentials → 401: it doesn't know who you are.
  • /api/me with a wrong password → 401.
  • /api/me as marta → 200, with ROLE_COACH.

And with @WithMockUser(username = "ana", roles = "ATHLETE"), the test starts with a ready-made SecurityContext, without going through authentication. Handy for testing authorization, but it doesn't test your users or passwords.

Step 9 of 9

Recap

  • Filters: DelegatingFilterProxy → FilterChainProxy → SecurityFilterChain, before the DispatcherServlet.
  • Configuration: a @Bean SecurityFilterChain with HttpSecurity (goodbye WebSecurityConfigurerAdapter).
  • Authentication: AuthenticationManager (ProviderManager) → DaoAuthenticationProvider → UserDetailsService + PasswordEncoder.
  • Result: an Authentication in the SecurityContextHolder (ThreadLocal).
  • 401 = not authenticated; 403 = not allowed (next lesson).

Cheatsheet →

Code

ManualAuthController.java

/** Before: every endpoint decodes the Authorization header and checks the password itself. */
public class ManualAuthController {
    public ResponseEntity<String> schedule(String authorization) {
        if (authorization == null || !authorization.startsWith("Basic ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        String[] userAndPassword = new String(Base64.getDecoder().decode(authorization.substring(6)),
            StandardCharsets.UTF_8).split(":", 2);
        if (!userAndPassword[0].equals("marta") || !userAndPassword[1].equals("wod123")) { // plain text!
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok("Monday: Fran");
    }
}

ArchitectureTest.java

@Test
void oneFilterChainProxyHoldsTheSecurityFilters() {
    var chain = springSecurityFilterChain.getFilterChains().getFirst();
    assertThat(chain.getFilters()).extracting(f -> f.getClass().getSimpleName())
        .contains("SecurityContextHolderFilter", "BasicAuthenticationFilter",
                  "ExceptionTranslationFilter", "AuthorizationFilter");  // in this order, among others
}

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();
}

ArchitectureTest.java

@Test
void theAuthenticationManagerDelegatesToAProvider() throws Exception {
    AuthenticationManager manager = authConfig.getAuthenticationManager();
    assertThat(manager).isInstanceOf(ProviderManager.class);
    assertThat(((ProviderManager) manager).getProviders()).hasAtLeastOneElementOfType(DaoAuthenticationProvider.class);

    Authentication ok = manager.authenticate(new UsernamePasswordAuthenticationToken("ana", "fran321"));
    assertThat(ok.isAuthenticated()).isTrue();
    assertThat(ok.getCredentials()).isNull();                          // erased after authentication
    assertThatThrownBy(() -> manager.authenticate(new UsernamePasswordAuthenticationToken("ana", "nope")))
        .isInstanceOf(BadCredentialsException.class);
}

MemberUserDetailsService.java

@Service
public class MemberUserDetailsService implements UserDetailsService { // "how do I find a user by name?"
    private final Map<String, UserDetails> members;

    public MemberUserDetailsService(PasswordEncoder encoder) {
        this.members = Map.of(
            "marta", User.withUsername("marta").password(encoder.encode("wod123")).roles("COACH").build(),
            "ana", User.withUsername("ana").password(encoder.encode("fran321")).roles("ATHLETE").build());
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        UserDetails member = members.get(username);
        if (member == null) {
            throw new UsernameNotFoundException(username); // never return null
        }
        return User.withUserDetails(member).build();    // a copy: the framework erases credentials
    }
}

ArchitectureTest.java

@Test
void passwordsAreStoredAsSaltedHashes() {
    String hash = encoder.encode("wod123");

    assertThat(hash).startsWith("{bcrypt}$2");                         // algorithm id + BCrypt hash
    assertThat(encoder.matches("wod123", hash)).isTrue();
    assertThat(encoder.encode("wod123")).isNotEqualTo(hash);           // random salt every time
}

BoxController.java

@GetMapping("/api/me")
public Map<String, Object> me(Authentication authentication,                  // injected by Spring MVC
                              @AuthenticationPrincipal UserDetails user) {    // the principal itself
    Authentication same = SecurityContextHolder.getContext().getAuthentication(); // thread-bound
    return Map.of(
        "name", authentication.getName(),
        "sameObject", same == authentication,
        "username", user.getUsername(),
        "authorities", authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList());
}

AuthenticationTest.java

@Test
void basicAuthenticationThroughTheFilterChain() throws Exception {
    mvc.perform(get("/api/public/timetable"))
        .andExpect(status().isOk());                                  // permitAll: no login
    mvc.perform(get("/api/me"))
        .andExpect(status().isUnauthorized());                        // 401: who are you?
    mvc.perform(get("/api/me").with(httpBasic("marta", "wrong")))
        .andExpect(status().isUnauthorized());                        // bad credentials: 401 too
    mvc.perform(get("/api/me").with(httpBasic("marta", "wod123")))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.name").value("marta"))
        .andExpect(jsonPath("$.authorities[0]").value("ROLE_COACH"))  // roles("COACH") → ROLE_COACH
        .andExpect(jsonPath("$.sameObject").value(true));
}

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();
}

Quiz

1. What's the difference between authentication and authorization?

2. What role does the DelegatingFilterProxy play?

3. Which interface do you implement to tell Spring Security how to load a user by name?

4. You call encoder.encode("wod123") twice with BCrypt. What do you get?

5. A request without credentials reaches an endpoint that requires authentication. What does Spring Security answer?

6. Where does Spring Security keep the Authentication of the current request's user?

Cheatsheet → · Mock exam →

Run it