Sub topic 4
Authentication flow, AuthenticationManager and SecurityContext
This chapter assumes you know what the security filter chain is and how to define a SecurityFilterChain bean. It also assumes you know the difference between authentication (who are you?) and authorization (what may you do?). Here you follow one request through authentication, step by step.
The main objects
Spring Security splits authentication into a few small types. Each has one job.
| Type | Role |
|---|---|
| `Authentication` | Holds the credentials going in, and the principal and authorities coming out. |
| `AuthenticationManager` | Entry point with one method, `authenticate`. |
| `ProviderManager` | The usual `AuthenticationManager`. It asks a list of providers in turn. |
| `AuthenticationProvider` | Checks one kind of credential, such as a username and password. |
| `SecurityContext` | Holds the current `Authentication`. |
| `SecurityContextHolder` | Gives code access to the `SecurityContext` for the current thread. |
An Authentication object exists in two states. Before checking, it is unauthenticated and holds only what the client sent, such as a username and password. After a successful check, it is authenticated and holds the principal (usually a UserDetails) and a list of granted authorities. Roles are authorities with the prefix ROLE_.
What happens on one request
Take an HTTP Basic request. The sequence is:
BasicAuthenticationFilterreads theAuthorizationheader and builds an unauthenticatedUsernamePasswordAuthenticationToken.- The filter passes the token to the
AuthenticationManager. ProviderManagerfinds a provider that supports this token type. For passwords this isDaoAuthenticationProvider.- The provider loads the user through
UserDetailsServiceand compares the password using thePasswordEncoder. - On success, the manager returns a fully populated, authenticated token.
- The filter stores it in the
SecurityContext. - Later filters, including the authorization filter, read it from there.
If the credentials are wrong, the provider throws an AuthenticationException. The filter then hands control to the AuthenticationEntryPoint, which produces the 401 response. A later chapter covers customizing it.
Reading the current user
Code in a controller can read the result without touching the holder directly. Spring MVC resolves an Authentication or Principal parameter from the context.
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class MeController {
@GetMapping("/api/me")
String me(Authentication authentication) {
return authentication.getName() + " has " + authentication.getAuthorities();
}
}For alice with the USER role, the response is alice has [ROLE_USER].
You can also read SecurityContextHolder.getContext().getAuthentication() anywhere in the same thread. This works because the holder stores the context in a ThreadLocal by default. Spring Security clears it at the end of each request, so one request never sees another request's user.
Exposing the AuthenticationManager
Spring Boot builds an AuthenticationManager for you when it finds a UserDetailsService and a PasswordEncoder bean. You rarely need to call it. If you write your own login endpoint, for example one that returns a token, you need the manager as a bean.
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
class AuthManagerConfig {
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
}Calling it by hand looks like this:
Authentication result = authenticationManager.authenticate(
UsernamePasswordAuthenticationToken.unauthenticated("alice", "change-me"));A wrong password throws BadCredentialsException. A successful call returns an authenticated token. Note that authenticate does not store the result. If you want the user to be recognized for the rest of the request, you must set it on the context yourself.
Common errors
- Expecting login to persist in a stateless API. With
STATELESS, nothing saves the context between requests. Each request must carry credentials, such as the Basic header or a bearer token. - Missing
PasswordEncoderbean. The provider then fails with "There is no PasswordEncoder mapped for the id null". Register one, as shown in the users and passwords chapter. - Sharing a context across threads. A new thread, such as an
@Asyncmethod, starts with an empty context unless you configure propagation.
Exercise
A custom login endpoint calls authenticationManager.authenticate(...) and gets a valid result, but a later call in the same request to SecurityContextHolder.getContext().getAuthentication() still returns null. Why, and how do you fix it?
Show answer
authenticate only returns the Authentication. It does not store it. Create a context, set the result on it, and save it with SecurityContextHolder.getContextHolderStrategy().setContext(context), or call SecurityContextHolder.getContext().setAuthentication(result).