Skip to content
thesarfo

Concept

Spring Security: Architecture

The core pieces of Spring Security's authentication flow — AuthenticationManager, AuthenticationProvider, UserDetailsService, and how they fit together with OncePerRequestFilter.

views 0

AuthenticationManager

The main interface for authentication in Spring Boot is AuthenticationManager, which has a single method:

public interface AuthenticationManager {
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
}

authenticate() can do one of three things:

  1. Return an Authentication (normally with authenticated=true) if it can verify the input represents a valid principal.
  2. Throw an AuthenticationException if it believes the input represents an invalid principal.
  3. Return null if it can’t decide.

AuthenticationProvider

AuthenticationManager doesn’t perform authentication itself — it delegates to an appropriate AuthenticationProvider, which is like the manager but with an extra method to let the caller check whether it supports a given Authentication type:

public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
}

The pieces, end to end

  1. UserDetailsService — has a method to load a user by username and return a UserDetails object Spring Security can use for authentication and validation.
  2. UserDetails — contains the information needed to build an Authentication object (username, password, authorities).
  3. UsernamePasswordAuthenticationToken — carries {username, password} from the login request; the AuthenticationManager uses it to authenticate the account.
  4. AuthenticationManager — uses a DaoAuthenticationProvider (with help from UserDetailsService and PasswordEncoder) to validate the UsernamePasswordAuthenticationToken. On success, it returns a fully populated Authentication object, including granted authorities.
  5. OncePerRequestFilter — executes once per request to the API. Its doFilterInternal() method is where you parse and validate the JWT, load user details (via UserDetailsService), and check authorization (via UsernamePasswordAuthenticationToken).
  6. AuthenticationEntryPoint — catches authentication errors.
  7. RepositoryUserRepository and RoleRepository, imported into the controller to work with the database.
  8. Controller — receives and handles the request after it’s passed through OncePerRequestFilter.