Sub topic 4
Authentication flow, AuthenticationManager and SecurityContext
This chapter assumes you can build a Spring Boot REST controller, write @Bean methods, and read a SecurityFilterChain like the one from the previous chapter. It covers what happens between "a request arrives with credentials" and "the controller can ask who the caller is". You will learn the roles of Authentication, AuthenticationManager, ProviderManager, AuthenticationProvider and SecurityContext, and the errors that come from misunderstanding them.
The objects involved
Spring Security splits authentication into small pieces. Each has one job.
| Type | Job |
|---|---|
| `Authentication` | Represents a request to authenticate, and later the result of it. |
| `AuthenticationManager` | Interface with one method, `authenticate(Authentication)`. |
| `ProviderManager` | The standard `AuthenticationManager`. It asks a list of providers in turn. |
| `AuthenticationProvider` | Knows how to check one kind of credential. |
| `SecurityContext` | Holds the `Authentication` for the current request. |
| `SecurityContextHolder` | Gives code access to the `SecurityContext`, by default through a thread-local. |
The Authentication object
The same interface is used before and after authentication. It exposes three things you will use often:
getPrincipal()returns who the caller is. Before authentication this is often a username string. Afterwards it is usually aUserDetailsobject, or aJwtfor token-based APIs.getCredentials()returns the proof, such as a password. After a successful login, Spring Security erases this value by default so the password does not linger in memory.getAuthorities()returns theGrantedAuthorityvalues. A role such asUSERappears here as the authorityROLE_USER.
isAuthenticated() tells you which state the object is in. A UsernamePasswordAuthenticationToken built with two arguments is unauthenticated. The three-argument constructor, which takes authorities, produces an authenticated token. Only trusted code should call that constructor.
How a request is authenticated
For HTTP Basic, the flow runs as follows.
The steps in words:
BasicAuthenticationFilterreads theAuthorization: Basic ...header and decodes the username and password.- It builds an unauthenticated
UsernamePasswordAuthenticationTokenand passes it to theAuthenticationManager. ProviderManagerwalks its providers and asks each whether itsupportsthat token type. The first that supports it gets to decide.DaoAuthenticationProviderloads the user throughUserDetailsService, checks the account flags, and compares the password using thePasswordEncoder.- On success it returns a new, fully authenticated token. The filter places it in the
SecurityContext. - On failure an
AuthenticationExceptionis thrown. The filter clears the context and hands the failure to theAuthenticationEntryPoint, which normally sends a 401 response.
If no credentials are present, the filter does nothing and the request continues unauthenticated. Rejection then happens later, at the authorization step, when the request needs an authenticated caller.
ProviderManager and multiple providers
A single application can accept several kinds of credentials. ProviderManager holds a list of providers and tries the ones that support the token type. If one throws AccountStatusException (for example, a locked account), the manager stops. If one throws a plain AuthenticationException such as BadCredentialsException, the manager remembers it and tries the next provider. If none succeeds, it throws the last exception.
A ProviderManager can also have a parent. If no provider can authenticate the request, the parent is consulted. Spring Boot's auto-configuration builds the default manager for you, which is why you rarely construct one by hand.
Exposing an AuthenticationManager
HTTP Basic does not require you to touch the manager. You need one when you write your own login endpoint, for example POST /api/login that accepts JSON credentials and returns a token. Expose the manager from AuthenticationConfiguration:
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();
}
}This manager is built from the UserDetailsService and PasswordEncoder beans in your context, using a DaoAuthenticationProvider. Here is a login controller that uses it:
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
public record LoginRequest(String username, String password) {}
public record LoginResponse(String username, java.util.List<String> authorities) {}
private final AuthenticationManager authenticationManager;
public LoginController(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@PostMapping("/public/login")
public LoginResponse login(@RequestBody LoginRequest request) {
Authentication token = UsernamePasswordAuthenticationToken
.unauthenticated(request.username(), request.password());
Authentication result = authenticationManager.authenticate(token);
return new LoginResponse(
result.getName(),
result.getAuthorities().stream().map(a -> a.getAuthority()).toList());
}
}If the credentials are wrong, authenticate throws BadCredentialsException. Because this call happens inside a controller, the security filter's entry point does not see it. Without your own handling, the client gets a 500 response, so catch AuthenticationException in a @ExceptionHandler and return 401. This method calls authenticate and returns the details, but it does not store the result anywhere. For a stateless API that is correct, because the client sends credentials or a token on every request.
The path /public/login matches the permitAll() rule from the earlier filter chain example.
The SecurityContext
The SecurityContext is a small holder with a getAuthentication() method. SecurityContextHolder stores it. By default it uses ThreadLocal, so the context belongs to the thread handling the request.
You can read the current caller in three ways:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
import java.util.Map;
@RestController
public class WhoAmIController {
@GetMapping("/api/me")
public Map<String, Object> me(Authentication authentication,
Principal principal,
@AuthenticationPrincipal UserDetails user) {
Authentication fromHolder = SecurityContextHolder.getContext().getAuthentication();
return Map.of(
"viaParameter", authentication.getName(),
"viaPrincipal", principal.getName(),
"viaAnnotation", user.getUsername(),
"viaHolder", fromHolder.getName());
}
}Prefer method parameters in controllers. They are easier to test than a static call to SecurityContextHolder. Note that @AuthenticationPrincipal UserDetails works only when the principal really is a UserDetails. With JWT authentication the principal is a Jwt, so the same endpoint would fail to inject, and you would use @AuthenticationPrincipal Jwt jwt instead.
Replacing the context safely
When you need to set the context yourself, create a new SecurityContext instead of mutating the shared one. This avoids races between threads:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
public class ContextUtil {
public static void setCurrent(Authentication authentication) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
}
}Persistence between requests
Setting the context lasts only for the current request unless something saves it. In a session-based app, SecurityContextHolderFilter loads the context at the start of each request from a SecurityContextRepository, and the default repository reads it from the HTTP session. In a stateless API, no session exists, so every request must authenticate from scratch. Basic and bearer-token filters do this on each call. The next chapter covers the session creation policy in detail.
At the end of the request, the context is cleared from the thread. This matters because servers reuse threads. If the context leaked from one request to the next, a caller could run with another user's identity.
Common errors and gotchas
- Context missing in new threads.
@Asyncmethods,CompletableFutureand manually created threads do not inherit the thread-local. UseDelegatingSecurityContextExecutororDelegatingSecurityContextRunnable, or configure a SpringTaskExecutorwrapped with the delegating variant. OtherwisegetAuthentication()returnsnull, or the anonymous token. - Anonymous is not null. For requests without credentials, Spring Security installs an
AnonymousAuthenticationTokenwith the principalanonymousUser. Code that checksauthentication == nullwill wrongly treat anonymous callers as logged in. Test forAnonymousAuthenticationTokenor callisAuthenticated()and check the type. - Unauthenticated token passed back as success. A custom provider that returns the input token without building a new authenticated one will leave the request unauthenticated.
- Wrong exception type. A custom provider should throw an
AuthenticationExceptionsubclass for bad credentials. ARuntimeExceptionescapesProviderManagerand produces a 500 response. - Returning
nullfrom a provider. Returningnullmeans "I cannot decide". The manager moves to the next provider. It is not a failure signal. - Username enumeration.
DaoAuthenticationProviderhides whether the username or the password was wrong by default and converts "user not found" intoBadCredentialsException. Do not undo this in your own handlers by sending different messages. - Credentials erased. After a successful login,
getCredentials()returnsnull. Do not rely on reading the password later.
A custom AuthenticationProvider
For a credential type that the built-in providers do not handle, such as an API key, write a provider. This one accepts a fixed key and grants the SERVICE role:
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
public class ApiKeyAuthenticationProvider implements AuthenticationProvider {
public static class ApiKeyToken extends AbstractAuthenticationToken {
private final String key;
public ApiKeyToken(String key) {
super(null);
this.key = key;
setAuthenticated(false);
}
public ApiKeyToken(String key, java.util.Collection<org.springframework.security.core.GrantedAuthority> authorities) {
super(authorities);
this.key = key;
setAuthenticated(true);
}
@Override public Object getCredentials() { return key; }
@Override public Object getPrincipal() { return "api-client"; }
}
private final byte[] expected;
public ApiKeyAuthenticationProvider(String expectedKey) {
this.expected = expectedKey.getBytes(StandardCharsets.UTF_8);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String supplied = (String) authentication.getCredentials();
byte[] suppliedBytes = supplied.getBytes(StandardCharsets.UTF_8);
if (!MessageDigest.isEqual(expected, suppliedBytes)) {
throw new BadCredentialsException("Invalid API key");
}
return new ApiKeyToken(supplied, AuthorityUtils.createAuthorityList("ROLE_SERVICE"));
}
@Override
public boolean supports(Class<?> authentication) {
return ApiKeyToken.class.isAssignableFrom(authentication);
}
}Three details deserve attention. The supports method is how ProviderManager picks a provider, so it must match your token class. The comparison uses MessageDigest.isEqual, which takes constant time and avoids leaking information about how many leading bytes matched. The success path returns a new authenticated token, not the input.
To use it, register the provider as a bean. Spring Boot then builds a ProviderManager that includes it:
@Bean
AuthenticationProvider apiKeyProvider() {
return new ApiKeyAuthenticationProvider("replace-with-a-secret-from-config");
}Registering a custom AuthenticationProvider bean makes Boot skip its default in-memory user, and with a single provider bean the auto-built manager may not include DaoAuthenticationProvider. If you need both username and password login and API keys, build a ProviderManager explicitly with both providers. You would also need a filter that reads the key header and calls the manager. The key itself belongs in configuration or a secret store, not in source code.
Exercise
A client sends a request with no credentials to an endpoint that requires authentication. Which component rejects it: the authentication filter, the AuthenticationManager, or the authorization step? What status code results, and what does the SecurityContext hold at that point?
Show answer
The authorization step rejects it. BasicAuthenticationFilter does nothing when the header is absent, so the AuthenticationManager is never called. The SecurityContext holds an AnonymousAuthenticationToken with the principal "anonymousUser". The authorization check finds an anonymous caller where an authenticated one is required, and the AuthenticationEntryPoint responds with 401.
Exercise
Your service method annotated with @Async calls SecurityContextHolder.getContext().getAuthentication() and gets null. Why, and how do you fix it?
Show answer
The SecurityContext is stored in a ThreadLocal, and the @Async method runs on a different thread from the request. Wrap the executor with DelegatingSecurityContextExecutor, or use DelegatingSecurityContextRunnable or Callable, so the context is copied to the worker thread for each task.