00:00

AuthenticationManager in Spring Security

Last updated:

AuthenticationManager is the single entry point Spring Security uses to answer one question: are these credentials valid? Login filters call it, and so can your own code. It receives an unauthenticated request, such as a username and password, and returns a fully authenticated user or throws an exception.

In this tutorial you will learn what AuthenticationManager and its main implementation, ProviderManager, do internally. Then you will use it to build a JSON login endpoint for a car-sharing API, including the step that most custom login code forgets: saving the login so the next request remembers it.

1. What Is AuthenticationManager?

AuthenticationManager is an interface with one method:

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

The argument is an Authentication object that holds the submitted credentials and is not yet authenticated. The method has three possible outcomes: return an authenticated Authentication (with authorities), throw an AuthenticationException such as BadCredentialsException when the credentials are wrong, or return null when it cannot decide.

Spring Security almost always uses ProviderManager as the implementation. It does not check passwords itself; it delegates to a list of AuthenticationProvider objects, each specialised for one kind of credential. The overall picture of these components is in Spring Security architecture.

2. Why AuthenticationManager Is Needed

Applications accept credentials in different shapes: a form post, a Basic header, a JSON body, a JWT or an API key. Without a common entry point, each login path would need its own password checks, account-lock checks and event publishing.

AuthenticationManager puts all of that behind one call. The built-in filters use it, and when you need a login path that Spring Security does not provide, such as a JSON login for a single-page app, you call the same manager and get exactly the same checks.

3. How ProviderManager Works

How ProviderManager delegates to authentication providersA login filter or controller calls ProviderManager.authenticate. ProviderManager asks each provider whether it supports the token type; DaoAuthenticationProvider handles username and password tokens using UserDetailsService and PasswordEncoder. If no provider can decide, the parent manager is asked. Login filter or your controller ProviderManager authenticate(token) DaoAuthenticationProvider supports UsernamePasswordAuthenticationToken JwtAuthenticationProvider supports BearerTokenAuthenticationToken Parent AuthenticationManager asked only if no provider decided
Figure 1: ProviderManager tries each provider that supports the token type, then falls back to its parent.
  1. A caller creates an unauthenticated token, for example UsernamePasswordAuthenticationToken.unauthenticated(username, password), and passes it to authenticate.
  2. ProviderManager loops over its providers and skips any whose supports(Class) method returns false for this token type.
  3. The first provider that returns an authenticated result wins. If a provider throws an AuthenticationException, ProviderManager remembers it and tries the remaining providers.
  4. If no provider decides, the optional parent manager is asked. If still nothing succeeds, the remembered exception (or a ProviderNotFoundException) is thrown.
  5. On success, ProviderManager erases the credentials (the password) from the result by default and publishes an authentication success event.

4. Important Classes and Methods

TypeRole
AuthenticationManagerThe interface: authenticate(Authentication)
ProviderManagerStandard implementation that delegates to a list of providers and an optional parent
AuthenticationProviderValidates one kind of token; declares what it handles with supports(Class)
UsernamePasswordAuthenticationTokenToken for username and password; create it with unauthenticated(...)
AuthenticationExceptionBase class of BadCredentialsException, DisabledException, LockedException and others
AuthenticationConfigurationGives access to the manager Spring Boot builds, via getAuthenticationManager()
SecurityContextRepositorySaves the authenticated context between requests, for example in the HTTP session
Important: Spring Security does not register AuthenticationManager as a bean that you can inject by default. Either declare it yourself, as in the example below, or obtain it from AuthenticationConfiguration.

5. A Complete Example: JSON Login for a Car-Sharing App

A car-sharing single-page app posts JSON to /api/login and then uses the session cookie for later calls, such as listing the user's trips. Because the browser holds a session cookie, CSRF protection stays on: the app first reads a CSRF token from /api/csrf. Built with Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.

package com.javabytechie.carshare;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/csrf", "/api/login", "/error").permitAll()
                .anyRequest().authenticated())
            // An API answers 401 instead of redirecting to a login page
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)));
        return http.build();
    }

    @Bean
    AuthenticationManager authenticationManager(UserDetailsService users, PasswordEncoder encoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider(users);
        provider.setPasswordEncoder(encoder);
        return new ProviderManager(provider);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        // Demo user only; real users come from a database
        return new InMemoryUserDetailsManager(
            User.withUsername("leela").password(encoder.encode("leela-pass")).roles("DRIVER").build());
    }
}

6. Step-by-Step Code Explanation

  1. Declaring the manager. The authenticationManager bean wraps a DaoAuthenticationProvider, which loads users from the UserDetailsService and checks the password with the PasswordEncoder. Declaring the bean makes it injectable into the controller.
  2. Creating the request token. UsernamePasswordAuthenticationToken.unauthenticated(...) builds a token whose isAuthenticated() is false. Passing an already-authenticated token would be a security bug, which is why this factory method exists.
  3. Handling failure. When the password is wrong, authenticate throws BadCredentialsException. The @ExceptionHandler turns every AuthenticationException into a 401 with a generic message, so attackers cannot learn whether a username exists.
  4. Saving the login. A successful authenticate call does not log anyone in by itself. The controller puts the result into a new SecurityContext and saves it with HttpSessionSecurityContextRepository. Since Spring Security 6, this explicit save is required; without it, the next request is anonymous again.
  5. Changing the session ID. Built-in login filters protect against session fixation automatically. A hand-written login must do it itself, here with request.changeSessionId().
  6. CSRF stays on. The login request carries the CSRF token from /api/csrf. A request without it is rejected before the controller runs.

7. Expected Output

The commands below save cookies to cookies.txt between calls, as a browser would:

Terminal
$ TOKEN=$(curl -s -c cookies.txt localhost:8080/api/csrf | jq -r .token)

$ curl -b cookies.txt -c cookies.txt -X POST localhost:8080/api/login -H "X-CSRF-TOKEN: $TOKEN" -H 'Content-Type: application/json' -d '{"username":"leela","password":"wrong-pass"}'
HTTP/1.1 401
{"error":"Invalid username or password"}

$ curl -b cookies.txt -c cookies.txt -X POST localhost:8080/api/login -H "X-CSRF-TOKEN: $TOKEN" -H 'Content-Type: application/json' -d '{"username":"leela","password":"leela-pass"}'
HTTP/1.1 200
{"authenticated":true,"user":"leela"}

$ curl -b cookies.txt localhost:8080/api/trips
HTTP/1.1 200
["leela: Indiranagar to Airport, 38 km"]

$ curl localhost:8080/api/trips
HTTP/1.1 401

$ curl -b cookies.txt -X POST localhost:8080/api/login -H 'Content-Type: application/json' -d '{"username":"leela","password":"leela-pass"}'
HTTP/1.1 403
{"timestamp":"2026-11-18T12:13:45.778Z","status":403,"error":"Forbidden","path":"/api/login"}

The wrong password produces the generic 401 message. The correct password returns 200, and from then on the session cookie alone is enough to list trips. A request without the cookie is anonymous and gets 401 from the entry point. The final login attempt omits the CSRF header and is rejected with 403 before AuthenticationManager is even called.

8. Advantages and Limitations

AdvantagesLimitations
One consistent entry point for every credential typeCalling it directly means you take over work the filters normally do: saving the context, session fixation, events
Providers can be added without touching callersNot exposed as a bean by default, which confuses many first-time users
Parent managers allow shared fallback authenticationA misconfigured parent can create surprising fallbacks or loops
Throws typed exceptions that map cleanly to 401 responsesError messages must be kept generic by you

9. Common Mistakes and Best Practices

  • Not saving the SecurityContext. Setting SecurityContextHolder lasts only for the current request. Save it with a SecurityContextRepository when you want a session login.
  • Creating a second ProviderManager by accident. If you declare an AuthenticationManager bean, make sure it contains every provider your filters need, because Spring Security uses your bean.
  • Leaking whether a user exists. Return the same message for unknown users and wrong passwords. DaoAuthenticationProvider also hides missing users as BadCredentialsException by default.
  • Disabling CSRF for a session-based JSON login. A browser sends the session cookie automatically, so the login and every later state-changing call need CSRF protection.
  • Prefer built-in login when it fits. formLogin() and httpBasic() already do everything the controller above does manually. Write your own endpoint only when the request format really differs.

10. Summary

  • AuthenticationManager.authenticate turns an unauthenticated token into an authenticated one or throws an AuthenticationException.
  • ProviderManager delegates to the providers that support the token type and falls back to an optional parent.
  • The manager is not an injectable bean by default; declare one or use AuthenticationConfiguration.
  • A custom login endpoint must save the SecurityContext and change the session ID itself.
  • Keep failure messages generic and keep CSRF protection for cookie-based logins.

11. References