Back to Spring Security: JWT, OAuth2, CSRF/CORS
Q6Question 6 of 11

AuthenticationManager and ProviderManager in Spring Security

Answer: AuthenticationManager is the single entry point for authentication in Spring Security; its default implementation, ProviderManager, delegates to a chain of AuthenticationProviders until one succeeds or all fail.

Key Concepts
  • AuthenticationManager is the main interface responsible for authenticating credentials in Spring Security; it has one method: authenticate(Authentication).
  • ProviderManager is the default implementation that holds a list of AuthenticationProvider instances and delegates to each one in order.
  • Each AuthenticationProvider handles a specific authentication type (username/password, JWT, LDAP) and declares what it supports via the supports() method.
  • DaoAuthenticationProvider is the most common provider; it uses UserDetailsService to load user data and PasswordEncoder to verify the password.
  • A successful authentication returns a fully populated Authentication object stored in SecurityContextHolder.
  • If no provider can authenticate the request, ProviderManager throws AuthenticationException (typically BadCredentialsException).

Definition

AuthenticationManager is the single entry point for authentication in Spring Security; its default implementation, ProviderManager, delegates to a chain of AuthenticationProviders until one succeeds or all fail.
  • AuthenticationManager – an interface with one method, authenticate(Authentication), that takes unauthenticated credentials and returns a fully authenticated principal or throws an exception.
  • ProviderManager – the default implementation that iterates through a list of AuthenticationProvider beans and delegates to the first one that supports the given authentication token type.
  • AuthenticationProvider – performs a specific type of authentication (e.g., DaoAuthenticationProvider for username/password, JwtAuthenticationProvider for JWT tokens).
  • Authentication – an object representing either unauthenticated credentials (before) or an authenticated principal with granted authorities (after).
  • SecurityContextHolder – stores the resulting Authentication so the rest of the application can access it.

Think of a bank's identity verification desk. The AuthenticationManager is the reception counter where you present your credentials. Behind the counter, there are multiple specialists (AuthenticationProviders): one checks passports (username/password), another checks employee badges (LDAP), another checks digital certificates (X.509). The receptionist (ProviderManager) passes your credentials to each specialist in order until one confirms your identity. If none can verify you, you are turned away.

Understanding the Concepts

What is AuthenticationManager?

AuthenticationManager is the core interface that Spring Security uses to authenticate a user. It has a single method:

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

You pass in an unauthenticated Authentication object (containing credentials like username and password), and the method returns a fully authenticated Authentication object (containing the principal, authorities, and details) or throws AuthenticationException if authentication fails.

What is ProviderManager?

ProviderManager is the default implementation of AuthenticationManager. It holds a list of AuthenticationProvider instances and tries each one in order.

JAVA
// Simplified internal logic of ProviderManager
public class ProviderManager implements AuthenticationManager {

    private List<AuthenticationProvider> providers;

    @Override
    public Authentication authenticate(Authentication authentication) {
        for (AuthenticationProvider provider : providers) {
            if (provider.supports(authentication.getClass())) {
                try {
                    return provider.authenticate(authentication);
                } catch (AuthenticationException e) {
                    // Try next provider
                }
            }
        }
        throw new ProviderNotFoundException("No provider found");
    }
}

The real implementation is more nuanced (it handles parent AuthenticationManagers, event publishing, and credential erasure), but this shows the core delegation pattern.

How does the full authentication flow work?

When a user submits login credentials to a banking application, the flow is:

  1. The user sends a POST request with username and password.
  2. A security filter (e.g., UsernamePasswordAuthenticationFilter) extracts the credentials.
  3. The filter creates an unauthenticated UsernamePasswordAuthenticationToken.
  4. The filter calls authenticationManager.authenticate(token).
  5. ProviderManager iterates through its providers.
  6. DaoAuthenticationProvider calls userDetailsService.loadUserByUsername(username).
  7. DaoAuthenticationProvider calls passwordEncoder.matches(rawPassword, storedHash).
  8. If the password matches, a fully authenticated UsernamePasswordAuthenticationToken is returned with the user's authorities.
  9. The filter stores the authentication in SecurityContextHolder.
  10. The request proceeds to the controller.
JAVA
package com.bank.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;

@Configuration
public class AuthManagerConfig {

    @Bean
    AuthenticationManager authenticationManager(
            AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
}

In Spring Boot, the AuthenticationManager is auto-configured. You only need to expose it as a bean if your code needs to call authenticate() directly, such as in a custom login endpoint.

How do you use AuthenticationManager in a custom login endpoint?

Some banking applications have a custom REST login endpoint instead of Spring Security's built-in form login:

JAVA
package com.bank.controller;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

@RestController
public class BankLoginController {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenService jwtTokenService;

    public BankLoginController(AuthenticationManager authenticationManager,
                                JwtTokenService jwtTokenService) {
        this.authenticationManager = authenticationManager;
        this.jwtTokenService = jwtTokenService;
    }

    @PostMapping("/api/login")
    public Map<String, String> login(@RequestBody LoginRequest request) {
        try {
            Authentication auth = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                    request.username(),
                    request.password()
                )
            );
            String token = jwtTokenService.generateToken(auth);
            return Map.of("token", token);
        } catch (AuthenticationException e) {
            throw new RuntimeException("Invalid credentials");
        }
    }
}

This is a legitimate use case. Standard form login and OAuth2 resource server flows already invoke the AuthenticationManager internally, so you do not need to call it directly in those cases.

What is the difference between AuthenticationManager and AuthenticationProvider?

AspectAuthenticationManagerAuthenticationProvider
RoleCoordinator: delegates to providersWorker: performs the actual authentication
Interface methodauthenticate(Authentication)authenticate(Authentication) + supports(Class)
ImplementationProviderManager (holds a list of providers)DaoAuthenticationProvider, JwtAuthenticationProvider, etc.
How manyTypically one per applicationMultiple, one per authentication mechanism
You callFrom filters or custom login endpointsRarely called directly; called by ProviderManager

What exceptions can occur?

AuthenticationManager throws subclasses of AuthenticationException:

ExceptionWhen it occurs
BadCredentialsExceptionPassword does not match the stored hash
UsernameNotFoundExceptionUserDetailsService cannot find the username
AccountExpiredExceptionThe account has expired
LockedExceptionThe account is locked (e.g., too many failed attempts)
DisabledExceptionThe account is disabled by an administrator
CredentialsExpiredExceptionThe password has expired and must be changed

By default, DaoAuthenticationProvider hides UsernameNotFoundException behind a generic BadCredentialsException to prevent username enumeration attacks. An attacker should not be able to determine whether a username exists based on the error message.

What are common mistakes?

The most common mistake is creating a fully authenticated token from unverified input:

JAVA
// WRONG: Never create an authenticated token from raw user input
Authentication auth = new UsernamePasswordAuthenticationToken(
    request.getUsername(),
    null,  // no password
    List.of(new SimpleGrantedAuthority("ROLE_ADMIN"))  // trusting user input
);
SecurityContextHolder.getContext().setAuthentication(auth);

// CORRECT: Always go through AuthenticationManager
Authentication auth = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(
        request.getUsername(),
        request.getPassword()
    )
);

The three-argument constructor of UsernamePasswordAuthenticationToken creates a trusted, authenticated token. Using it with unverified data bypasses all security checks.

What should a senior engineer know?

  • ProviderManager can have a parent AuthenticationManager. If no local provider can authenticate the request, it delegates to the parent. This is useful in multi-tenant setups where a common parent handles shared authentication.
  • After successful authentication, ProviderManager erases credentials from the Authentication object by default (eraseCredentialsAfterAuthentication = true). This prevents passwords from lingering in memory.
  • You can publish authentication success and failure events by registering an AuthenticationEventPublisher. This is useful for audit logging in banking applications.
  • In reactive applications (WebFlux), the equivalent is ReactiveAuthenticationManager.

Visual Overview

DIAGRAM
┌───────────────────────────────────────────────┐
│       POST /api/login                          │
│       { username: "rajesh", password: "***" }  │
└──────────────────────┬────────────────────────┘
                       │
                       ▼
┌───────────────────────────────────────────────┐
│  UsernamePasswordAuthenticationFilter          │
│  Creates: UsernamePasswordAuthenticationToken  │
│           (unauthenticated)                    │
└──────────────────────┬────────────────────────┘
                       │
                       ▼
┌───────────────────────────────────────────────┐
│         AuthenticationManager                  │
│         (ProviderManager)                      │
└──────────────────────┬────────────────────────┘
                       │
          ┌────────────┼────────────┐
          ▼            ▼            ▼
   ┌────────────┐ ┌──────────┐ ┌──────────┐
   │ DaoAuth    │ │ LDAP     │ │ JWT      │
   │ Provider   │ │ Provider │ │ Provider │
   │ supports?  │ │supports? │ │supports? │
   │   YES      │ │   NO     │ │   NO     │
   └─────┬──────┘ └──────────┘ └──────────┘
         │
         ▼
┌────────────────────────────┐
│  UserDetailsService        │
│  loadUserByUsername()      │
└────────────┬───────────────┘
             │
             ▼
┌────────────────────────────┐
│  PasswordEncoder           │
│  matches(raw, stored)      │
└────────────┬───────────────┘
             │
             ▼
┌────────────────────────────┐
│  Authenticated Token       │
│  (principal + authorities) │
└────────────┬───────────────┘
             │
             ▼
┌────────────────────────────┐
│  SecurityContextHolder     │
│  stores Authentication     │
└────────────────────────────┘

Key Takeaway

AuthenticationManager is the single gateway through which all authentication flows in Spring Security. Whether a user logs in with a form, submits a JWT bearer token, or authenticates via LDAP, the AuthenticationManager is the interface that coordinates the process.

Its default implementation, ProviderManager, follows the chain of responsibility pattern. It holds a list of AuthenticationProvider instances, each specialized in a particular authentication type. When credentials arrive, ProviderManager asks each provider whether it supports the given token type and delegates to the first one that does. For username and password authentication, DaoAuthenticationProvider loads user details and verifies the password hash.

In a banking application at National Bank of India, Rajesh would have the AuthenticationManager auto-configured by Spring Boot. The application defines a UserDetailsService bean that loads banker details from the database and a PasswordEncoder bean that uses BCrypt. When a teller logs in, the filter creates an unauthenticated token, the AuthenticationManager delegates to DaoAuthenticationProvider, and a successful match produces an authenticated token stored in SecurityContextHolder.

The critical safety rule is to never manually create an authenticated token from unverified input. The three-argument constructor of UsernamePasswordAuthenticationToken marks the token as trusted. Only the AuthenticationManager should produce authenticated tokens after proper credential verification.

The one sentence to remember: AuthenticationManager is the coordinator that delegates to AuthenticationProviders, and ProviderManager tries each provider in order until one succeeds or all fail.

---

Share
Use ← → arrow keys to navigate