How a login is actually verified

Spring Security · lesson 16 of 31 · 4 min read

Follow a username and password from the login filter into ProviderManager and back out again.

Open this lesson in the learning hub

Key points

  • The login filter builds an unauthenticated token and hands it to the AuthenticationManager.
  • The default manager is ProviderManager. It walks its providers and uses the first whose supports() says yes.
  • DaoAuthenticationProvider is the one that calls your UserDetailsService and your PasswordEncoder.
  • A provider returning null means "not mine, try the next one". Throwing an AuthenticationException ends the walk.
  • On success it returns a new authenticated token carrying the authorities, and erases the raw password from it.
  • Inject AuthenticationManager into a custom /login endpoint instead of comparing passwords by hand.

Example

@Bean
AuthenticationManager authenticationManager(UserDetailsService uds, PasswordEncoder encoder) {
    DaoAuthenticationProvider dao = new DaoAuthenticationProvider();
    dao.setUserDetailsService(uds);
    dao.setPasswordEncoder(encoder);
    return new ProviderManager(dao);          // providers are walked in order
}

@PostMapping("/api/auth/login")
public TokenResponse login(@RequestBody LoginRequest body) {
    Authentication result = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(body.email(), body.password()));

    // result is a different object: authenticated, with authorities, credentials erased
    return new TokenResponse(jwtService.issue(result));
}

The manager never checks a password - it finds the provider that will.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.