Spring Security is the de facto standard for securing Java applications, offering robust support for OAuth2, LDAP, and standard form logins. But what happens when “standard” isn’t enough?
You might face a scenario where user credentials live in a legacy mainframe, a proprietary API, or a multi-tenant database with complex sharding rules. In these cases, the default DaoAuthenticationProvider fails. Trying to hack standard filters to fit these requirements leads to brittle code, security vulnerabilities, and maintenance nightmares.
The solution lies in Spring Security’s modular architecture. By implementing a Custom Authentication Provider, you can inject your specific business logic directly into the security lifecycle without compromising the framework’s integrity.
This guide is rebuilt for Spring Boot 4.1 and Spring Security 7.1, and it is now written to be read once, top to bottom. It starts with the smallest provider that works, then adds what real projects need next: password hashing, a second provider behind the same login form, a one-time-code step for admins, and a JWT-secured API living in the same application. Every behaviour described below is an assertion in a test that was run, and the real output is quoted next to the claim.
Verified against. Spring Boot 4.1.2 (Spring Framework 7.0.10, Spring Security 7.1.2; both artifacts were published to Maven Central on 2026-10-22, and the 4.1.0 / 7.1.0 line on 2026-06-10 / 2026-06-09), Tomcat 11.0.27 (Jakarta EE 11 / Servlet 6.1), Java 17 minimum, compiled and tested on JDK 25 (Temurin 25.0.5, the current LTS).
Where this article says what a Spring Security class does internally, the code quoted is from the 7.1.2 sources jar on Maven Central, and every behavioural claim is backed by one of the tests in the download below.
Download everything. There is no Git repository for this article. Every code block on this page links to its own .java file in this site’s media library, and custom-auth-provider-demo.zip holds the whole Maven project (9 tests, JDK 25: run mvn test). The captured output of every test run is in custom-auth-provider-test-output.txt.
What this revision corrects. The previous revision of this article was wrong in three places, and writing the tests exposed all three. (1) It said a provider that throws an exception makes authentication fail “immediately”; in fact only account-status exceptions do — aBadCredentialsExceptionjust moves the search to the next provider (section 3). (2) Its test table promised401 Unauthorizedfor a failed form login; the real answer is a302redirect to/login?error(section 2). (3) It said a hand-builtAuthenticationManagerbean “disables” provider auto-registration; the opposite is closer to the truth — with a single provider bean the hand-built manager is ignored (section 7).
1. Where your code fits: four objects between a login form and your data
Before writing code, it is crucial to understand where your custom logic fits. Spring Security uses a delegation model.
- AuthenticationFilter: Intercepts the request.
- AuthenticationManager: The interface defining how authentication is processed.
- ProviderManager: The standard implementation that iterates through a list of providers.
- AuthenticationProvider: The component that actually validates the user.
Your code lives in the last box only. When you write a custom provider you are adding a new “voter” to the ProviderManager’s list, and the manager asks each voter in order. The diagram shows the five things a provider can answer and what the manager does with each. Keep it open while you read section 3 — every row of it is a test there.
Read the right-hand column top to bottom: a token ends the search with success, null means “not mine”, two common exceptions are remembered while the search continues, and only an account-status exception ends it early. If nobody answers at all, you get ProviderNotFoundException — a name worth recognising now, because section 7 shows the quiet way to cause it.
How does the manager know which provider to ask? (supports() and token types)
Before calling a provider, ProviderManager asks provider.supports(tokenClass). A form login produces a UsernamePasswordAuthenticationToken, so only providers that return true for that class are called. This is also how one application can host providers for entirely different proofs: section 6 adds a provider for a custom OtpAuthenticationToken, and the username/password providers never see it. The test providerThatDoesNotSupportTheTokenIsNeverCalled in ProviderManagerSemanticsTests.java pins this down.
Going deeper
2. The smallest provider that works
Step 1: Project setup and dependencies
Start from a Spring Boot 4.1 application with Maven. The spring-boot-starter-security-oauth2-resource-server dependency is only needed from section 8 onwards, and the two test starters are what make the output below reproducible. The full pom.xml is inside the project zip.
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Java 25, not 17. Framework 7 kept the Java 17 floor, but the Spring team’s own guidance is to run the latest LTS, and everything in this article was compiled and tested on JDK 25.
Step 2: Implement the provider
The heart of this implementation is the AuthenticationProvider interface. You override two methods:
authenticate: Contains the logic to verify credentials.supports: Tells Spring Security which token type this provider can handle (usuallyUsernamePasswordAuthenticationToken).
This version, CustomAuthProvider.java, is deliberately naive — it compares plain text. Section 4 replaces the credential check with a real PasswordEncoder once you have seen why the naive version is a liability.
package com.ankurm.authdemo.auth;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.ArrayList;
import java.util.List;
/**
* The smallest working AuthenticationProvider. Deliberately naive: it compares
* plain-text passwords. EncodedCustomAuthProvider is the version you would ship.
*/
public class CustomAuthProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 1. Extract credentials from the authentication object
String username = authentication.getName();
String password = authentication.getCredentials().toString();
// 2. VALIDATION LOGIC
// In a real app, inject a Service or Repository here to check DB/External API
if ("admin".equals(username) && "secret".equals(password)) {
return createSuccessfulAuth(username, password, "ROLE_ADMIN", "ROLE_USER");
} else if ("user".equals(username) && "password".equals(password)) {
return createSuccessfulAuth(username, password, "ROLE_USER");
}
// 3. Fail explicitly if credentials don't match
throw new BadCredentialsException("Invalid credentials provided");
}
// Helper method to construct the authenticated token
private Authentication createSuccessfulAuth(String username, String password, String... roles) {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
// IMPORTANT: The third argument (authorities) marks the token as authenticated
return new UsernamePasswordAuthenticationToken(username, password, authorities);
}
@Override
public boolean supports(Class<?> authenticationType) {
// Ensure this provider only processes standard username/password tokens
return authenticationType.equals(UsernamePasswordAuthenticationToken.class);
}
}
Step 3: Wire the configuration
The 2025 version of this article manually built a ProviderManager and exposed it as an AuthenticationManager bean. You do not need that bean for a single provider: this is the whole configuration, from BasicSecurityConfig.java. Section 7 shows exactly what the old bean did and did not do.
package com.ankurm.authdemo.config;
import com.ankurm.authdemo.auth.CustomAuthProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@Profile("basic")
public class BasicSecurityConfig {
@Bean
public CustomAuthProvider customAuthProvider() {
return new CustomAuthProvider();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// Attach the provider directly to this chain
.authenticationProvider(customAuthProvider())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
// Spring Security's built-in generated login page -- no /login
// controller or template required to get this running
.formLogin(Customizer.withDefaults())
.logout(Customizer.withDefaults());
return http.build();
}
}
Note on the original example. The 2025 version pointed.loginPage("/login")at a controller that was never shown, which 404s on a fresh checkout.Customizer.withDefaults()uses Spring Security’s own generated login page instead — correct out of the box, and a custom page is a one-line swap once you have a template to point it at.
Step 4: Verify it
A REST controller with endpoints protected by different roles (TestController.java; the /api/ping and /whoami methods are used in later sections):
package com.ankurm.authdemo.web;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
@GetMapping("/public/status")
public String publicEndpoint() {
return "Public access - System Healthy";
}
@GetMapping("/user/dashboard")
public String userDashboard() {
return "User content - Visible to USER and ADMIN";
}
@GetMapping("/admin/panel")
public String adminPanel() {
return "Admin Content - RESTRICTED";
}
@GetMapping("/api/ping")
public String apiPing() {
return "pong from the JWT-protected API";
}
/** Debug helper: prints who the framework thinks you are. Delete before shipping. */
@GetMapping("/whoami")
public List<String> whoami(Authentication authentication) {
return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).sorted().toList();
}
}
The scenario matrix below is a test, not a table somebody typed: BasicProviderTests.java posts the same form a browser would send and records what comes back. This is its real output from the test-output file (block 02):
ENDPOINT CREDENTIALS STATUS
/public/status none 200
/user/dashboard none 302
/user/dashboard user/password 200
/admin/panel user/password 403
/admin/panel admin/secret 200
/profile none 302
POST /login user/password -> 302 -> /
POST /login admin/secret -> 302 -> /
POST /login invalid/invalid -> 302 -> /login?error
| Endpoint | Credentials used | Actual HTTP status | Explanation |
|---|---|---|---|
/public/status | None | 200 OK | Publicly accessible. |
/user/dashboard | user / password | 200 OK | Authenticated as User. |
/admin/panel | user / password | 403 Forbidden | Valid login, but insufficient role. |
/admin/panel | admin / secret | 200 OK | Authenticated as Admin. |
/user/dashboard or /profile | None | 302 Found | Not logged in: redirected to the login page. |
POST /login | invalid / invalid | 302 Found to /login?error | Authentication failed. |
A failed form login is not a 401. The previous revision of this table said401 Unauthorizedfor bad credentials. WithformLogin()the framework redirects instead; a 401 only appears from entry points built for APIs (HTTP Basic, bearer tokens — section 8 shows one). If your client is a script and you want a 401, you want a different authentication mechanism, not a different provider.
Why 302 and not 401? (entry points in one paragraph)
Each authentication mechanism brings its own entry point — the thing that answers “you are not logged in”. formLogin()’s entry point redirects a browser to the login page; httpBasic() and the bearer-token filter answer 401 with a WWW-Authenticate header. The provider never chooses between them. It only decides who the user is; the mechanism decides how a failure is presented. That is why the same CustomAuthProvider yields a 302 in this section and could yield a 401 on an API chain.
Going deeper
- Every request and response above is in BasicProviderTests.java; the generated login page is Spring Security’s own, so no template is needed to run it.
- Authentication Architecture (entry points, filters, the SecurityContext)
3. A provider has three ways to answer — and the manager treats each differently
Return a token and you are done. Return null and you are saying “this login is not mine, ask someone else”. Throw, and the outcome depends on which exception. That last rule is the one most tutorials get wrong, including the previous revision of this one, so it is tested directly: ProviderManagerSemanticsTests.java builds a ProviderManager from two stub providers and records what comes back for each pairing. Real output (block 01):
Provider A answers, then provider B answers. What does ProviderManager return?
A throws BadCredentialsException, B succeeds -> authenticated as from-B
A throws AuthenticationServiceException, B succeeds -> authenticated as from-B
A throws LockedException, B succeeds -> failed with LockedException
A throws InternalAuthenticationServiceException, B succeeds -> failed with InternalAuthenticationServiceException
A returns null, B succeeds -> authenticated as from-B
A throws BadCredentialsException, B returns null -> failed with BadCredentialsException
A returns null, B returns null -> failed with ProviderNotFoundException
Four lines carry the lesson. A BadCredentialsException from provider A did not stop provider B from authenticating the user. An AuthenticationServiceException did not either. A LockedException and an InternalAuthenticationServiceException did stop it. And when B returns null after A threw, the final answer is A’s exception, not ProviderNotFoundException — the manager remembers the last error it saw.
How a provider signals its verdict.nullmeans “not mine” and the manager tries the next provider. ABadCredentialsExceptionor a plainAuthenticationServiceExceptionis remembered, and the manager still tries the next provider. Only anAccountStatusException(LockedException,DisabledException,AccountExpiredException,CredentialsExpiredException) or anInternalAuthenticationServiceExceptionstops the search on the spot. The old advice “if it throws an exception, authentication fails immediately” was wrong.
The practical consequence: with several providers, the exception you throw is a routing decision. If your provider knows the account is locked, say so with LockedException and nobody downstream can override it. If it merely did not recognise the user, return null (or throw BadCredentialsException if you are happy for others to try).
The exceptions worth knowing and what each means to a user
BadCredentialsException— wrong username/password. The standard failure; the manager moves on to the next provider.LockedException/DisabledException— the account exists but should not authenticate right now. Distinct from bad credentials, worth distinct client-facing messages, and (as the output above shows) final.AuthenticationServiceException— the provider itself failed (a downstream API is down, a database timed out). This is a system error, not a credentials error; conflating the two tells users to retry a password that was never wrong. UseInternalAuthenticationServiceExceptioninstead when you want that failure to end the search rather than fall through.
Going deeper
- Try it yourself: swap the order of the providers in ProviderManagerSemanticsTests.java and re-run to watch each row change.
- ProviderManager Javadoc (the exception rules are documented on authenticate())
4. Never compare passwords as plain text
Never compare plain text passwords in production logic, the way section 2’s provider does (password.equals("secret")). Inject a PasswordEncoder and compare hashes. This is EncodedCustomAuthProvider.java. It also adds a FACTOR_PASSWORD authority, which section 6 uses to record how a user proved who they are:
package com.ankurm.authdemo.auth;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.FactorGrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.List;
import java.util.Map;
/**
* Same contract as CustomAuthProvider, but compares hashes instead of plain text.
* Throws BadCredentialsException for an unknown user or a wrong password, so the
* ProviderManager moves on to the next provider (see ProviderManagerSemanticsTests).
*/
public class EncodedCustomAuthProvider implements AuthenticationProvider {
private final PasswordEncoder passwordEncoder;
// Stand-in for a real lookup (DB, legacy API, ...). Passwords are hashes,
// never plain text.
private final Map<String, String> encodedPasswordsByUsername;
public EncodedCustomAuthProvider(PasswordEncoder passwordEncoder,
Map<String, String> encodedPasswordsByUsername) {
this.passwordEncoder = passwordEncoder;
this.encodedPasswordsByUsername = encodedPasswordsByUsername;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String rawPassword = authentication.getCredentials().toString();
String encoded = encodedPasswordsByUsername.get(username);
if (encoded == null || !passwordEncoder.matches(rawPassword, encoded)) {
throw new BadCredentialsException("Invalid credentials provided");
}
// Credentials are null on purpose: finish all password handling in this method.
// The PASSWORD factor records HOW the user proved who they are (used by the MFA rule).
return UsernamePasswordAuthenticationToken.authenticated(username, null,
List.of(new SimpleGrantedAuthority("ROLE_USER"),
FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY)));
}
@Override
public boolean supports(Class<?> authenticationType) {
return authenticationType.equals(UsernamePasswordAuthenticationToken.class);
}
}
The returned token carries null credentials on purpose. Spring Security erases credentials from the Authentication after a successful login anyway, and a test proves it (ProviderManagerSemanticsTests.java, block 08):
provider returned a token carrying credentials = still-the-raw-password
after ProviderManager.authenticate(): credentials = null
Erasing credentials. Spring Security erases the password from theAuthenticationobject after a successful login, to keep it out of heap dumps. If your provider needs the raw password for anything afterauthenticate()returns, it will already be null — finish all credential handling inside the method itself.
Which encoder? (what createDelegatingPasswordEncoder() gives you)
The next section builds its users with PasswordEncoderFactories.createDelegatingPasswordEncoder(). It stores hashes with an {id} prefix (the default id is bcrypt), so you can change algorithms later without invalidating existing rows: old hashes keep their old prefix and still verify. That prefix is why you must treat a stored hash as an opaque string and never compare it yourself.
Going deeper
- Authentication Architecture (password storage)
- Spring Security 6 to 7 Migration Guide — for anything that changed around encoders and authorization
5. Two providers behind one login form
Real systems end up with two places that know about users: your own table, and the legacy directory you were hired to bridge. Section 3 already told you how the manager behaves, so this is mostly a matter of ordering. LayeredSecurityConfig.java builds both providers, attaches them to the chain explicitly, and puts the internal provider first:
public SecurityFilterChain filterChain(HttpSecurity http,
EncodedCustomAuthProvider internalProvider,
LegacyDirectoryAuthProvider legacyProvider) throws Exception {
AuthorizationManagerFactory<RequestAuthorizationContext> adminNeedsTwoFactors =
AuthorizationManagerFactories.<RequestAuthorizationContext>multiFactor()
.requireFactors(FactorGrantedAuthority.PASSWORD_AUTHORITY,
FactorGrantedAuthority.OTT_AUTHORITY)
.build();
http
// ORDER MATTERS: ProviderManager asks them top to bottom.
.authenticationProvider(internalProvider)
.authenticationProvider(legacyProvider)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").access(adminNeedsTwoFactors.hasRole("ADMIN"))
.requestMatchers("/user/**", "/whoami", "/mfa/**").authenticated()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults());
return http.build();
The second provider, LegacyDirectoryAuthProvider.java, uses all three answers from section 3: null for “not my user”, LockedException as a final verdict, and AuthenticationServiceException when the backend is down:
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String rawPassword = authentication.getCredentials().toString();
LegacyUser user;
try {
user = directory.find(username).orElse(null);
} catch (DirectoryUnavailableException ex) {
// A system failure, not a credentials failure.
throw new AuthenticationServiceException("Legacy directory unavailable", ex);
}
if (user == null) {
return null; // not my user: let the next provider decide
}
if (user.locked()) {
throw new LockedException("Account locked");
}
if (!passwordEncoder.matches(rawPassword, user.passwordHash())) {
throw new BadCredentialsException("Invalid credentials provided");
}
List<GrantedAuthority> authorities = new ArrayList<>();
user.roles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
authorities.add(FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY));
return UsernamePasswordAuthenticationToken.authenticated(username, null, authorities);
Supporting classes: the LegacyDirectory interface and the audit listener
The directory is an interface so a test can switch the “mainframe” off (LegacyDirectory.java):
package com.ankurm.authdemo.auth;
import java.util.List;
import java.util.Optional;
/** Stand-in for the mainframe / proprietary API that actually holds some of your users. */
public interface LegacyDirectory {
/** @throws DirectoryUnavailableException when the backend cannot be reached */
Optional<LegacyUser> find(String username);
record LegacyUser(String username, String passwordHash, List<String> roles, boolean locked) { }
class DirectoryUnavailableException extends RuntimeException {
public DirectoryUnavailableException(String message) {
super(message);
}
}
}And the listener that records which verdict the manager reached, used by the test below (AuthenticationAudit.java):
package com.ankurm.authdemo.web;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** Which verdict did the ProviderManager reach? The event class name says it. */
@Component
public class AuthenticationAudit {
private final List<String> events = new CopyOnWriteArrayList<>();
@EventListener
public void on(AbstractAuthenticationEvent event) {
events.add(event.getClass().getSimpleName() + " user=" + event.getAuthentication().getName());
}
public List<String> events() {
return List.copyOf(events);
}
public void clear() {
events.clear();
}
}Now the test. LayeredProviderTests.java logs in five different people, then switches the legacy directory off and tries again. The last column is the event Spring published, which is the quickest way to see which verdict the manager reached (block 03):
Chain order: EncodedCustomAuthProvider (internal users) -> LegacyDirectoryAuthProvider (mainframe)
user/password 302 -> / AuthenticationSuccessEvent + InteractiveAuthenticationSuccessEvent
/whoami -> ["FACTOR_PASSWORD","ROLE_USER"]
admin/secret 302 -> / AuthenticationSuccessEvent + InteractiveAuthenticationSuccessEvent
/whoami -> ["FACTOR_PASSWORD","ROLE_ADMIN","ROLE_USER"]
locked/secret 302 -> /login?error AuthenticationFailureLockedEvent
ghost/whatever 302 -> /login?error AuthenticationFailureBadCredentialsEvent
admin/wrong 302 -> /login?error AuthenticationFailureBadCredentialsEvent
-- legacy directory switched off --
user/password 302 -> / AuthenticationSuccessEvent + InteractiveAuthenticationSuccessEvent
admin/secret 302 -> /login?error AuthenticationFailureServiceExceptionEvent
Reading it top to bottom: user is answered by the internal provider. admin is not in the internal map, so provider A throws BadCredentialsException — and section 3 told us that does not stop provider B, which authenticates the admin. locked ends with a locked-account event because that exception is final. ghost and admin/wrong end as bad credentials. With the directory off, user still logs in (provider A answers before B is ever asked) but admin fails with a service-exception event, which is exactly the system-error-versus-credentials distinction from section 3.
Order is behaviour. Put the cheapest and most certain provider first. In the run above, an internal user is never delayed by the legacy directory, and never fails because of it — but an admin is only as available as that directory. If you want a directory outage to be a hard stop instead of a fall-through, throw InternalAuthenticationServiceException from the provider.
Debugging: which provider actually ran?
Stepping through ProviderManager.authenticate() in a debugger is slow: it is a loop over an interface with no provider names attached. Listen for events instead. Spring Security 7.1.2’s HttpSecurityConfiguration wires an event publisher into each chain’s builder automatically — your own AuthenticationEventPublisher bean if you define one, otherwise a DefaultAuthenticationEventPublisher (the line authenticationBuilder.authenticationEventPublisher(getAuthenticationEventPublisher()) is in the source quoted in section 7) — so you only need an @EventListener for AbstractAuthenticationEvent — that is all AuthenticationAudit above does. A successful login fires AuthenticationSuccessEvent from the manager followed by InteractiveAuthenticationSuccessEvent from the form-login filter; a failure fires one event named after the exception, as in the output above.
Going deeper
- Reorder the two
.authenticationProvider(...)calls and re-run LayeredProviderTests.java to watch the table change. - Spring Security 7.1 JWT Authentication: The Complete Guide — the same “which verdict, which exception” thinking for bearer tokens
6. Adding a second factor with a provider (the MFA hook)
A custom provider is also the natural place to prove a second thing about a user. Spring Security 7 has first-class vocabulary for this: every authentication method grants a FactorGrantedAuthority (FACTOR_PASSWORD, FACTOR_OTT, and so on), and an authorization rule can require several of them at once. Sections 4 and 5 already grant FACTOR_PASSWORD. What is missing is a provider that grants FACTOR_OTT after checking a one-time code.
Because it is a different proof, it gets a different token type. OtpAuthenticationToken.java carries the already-logged-in user plus the code:
package com.ankurm.authdemo.mfa;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import java.util.Collection;
import java.util.List;
/**
* A different token TYPE for a different proof: "this already-logged-in user also knows the one-time code".
* Because it is its own type, only a provider whose supports() accepts it will ever see it.
*/
public class OtpAuthenticationToken extends AbstractAuthenticationToken {
private final Authentication current; // who is already logged in
private final String code;
public OtpAuthenticationToken(Authentication current, String code) {
super(List.of());
this.current = current;
this.code = code;
}
public Authentication current() {
return current;
}
@Override
public Object getCredentials() {
return code;
}
@Override
public Object getPrincipal() {
return current.getPrincipal();
}
}
And OtpStepUpProvider.java checks the code, keeps every authority the user already had, and adds the new factor. Note that supports() accepts only the OTP token, so the username/password providers never see it:
package com.ankurm.authdemo.mfa;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.FactorGrantedAuthority;
import java.util.ArrayList;
import java.util.List;
/** The MFA hook: keeps every authority the user already has and adds the one-time-token factor. */
public class OtpStepUpProvider implements AuthenticationProvider {
private final OtpVerifier verifier;
public OtpStepUpProvider(OtpVerifier verifier) {
this.verifier = verifier;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OtpAuthenticationToken otp = (OtpAuthenticationToken) authentication;
Authentication current = otp.current();
String username = current.getName();
if (!verifier.verify(username, String.valueOf(otp.getCredentials()))) {
throw new BadCredentialsException("Invalid one-time code");
}
List<GrantedAuthority> authorities = new ArrayList<>(current.getAuthorities());
authorities.add(FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.OTT_AUTHORITY));
return UsernamePasswordAuthenticationToken.authenticated(current.getPrincipal(), null, authorities);
}
@Override
public boolean supports(Class<?> authenticationType) {
return OtpAuthenticationToken.class.isAssignableFrom(authenticationType);
}
}
The controller (OtpController.java) hands the code to a ProviderManager that contains only this provider, then stores the upgraded authentication in the session:
public ResponseEntity<String> verify(@RequestParam String code, Authentication current,
HttpServletRequest request, HttpServletResponse response) {
Authentication upgraded;
try {
upgraded = otpManager.authenticate(new OtpAuthenticationToken(current, code));
} catch (AuthenticationException ex) {
return ResponseEntity.status(401).body("second factor rejected");
}
SecurityContext context = strategy.createEmptyContext();
context.setAuthentication(upgraded);
strategy.setContext(context);
repository.saveContext(context, request, response); // without this the upgrade dies with the request
return ResponseEntity.ok("second factor accepted for " + upgraded.getName());
ForgetsaveContextand the upgrade vanishes. I removed therepository.saveContext(...)line and re-ran the test: the endpoint still answered200, but the next request to/admin/panelwas still403and/whoamistill showed noFACTOR_OTT. Setting theSecurityContextonly affects the current request; the session is what carries it to the next one. (This is the classic “login works, the next request is anonymous” bug, in MFA form.)
The rule itself is a few lines in LayeredSecurityConfig.java: build an authorization-manager factory that demands both factors, and use it for /admin/** only:
AuthorizationManagerFactory<RequestAuthorizationContext> adminNeedsTwoFactors =
AuthorizationManagerFactories.<RequestAuthorizationContext>multiFactor()
.requireFactors(FactorGrantedAuthority.PASSWORD_AUTHORITY,
FactorGrantedAuthority.OTT_AUTHORITY)
.build();
.requestMatchers("/admin/**").access(adminNeedsTwoFactors.hasRole("ADMIN"))
Four requests tell the whole story (diagram first, then the test’s own output from LayeredProviderTests.java, block 04):
The role never changes between step 2 and step 4 — only the set of proven factors does. That is the point of keeping factors as authorities: the authorization rule stays declarative, and the provider is the only code that knows how a code is checked.
The same four requests as recorded by the test (test-output file, block 04):
admin logs in with password only
GET /user/dashboard -> 200
GET /admin/panel -> 403
GET /whoami -> ["FACTOR_PASSWORD","ROLE_ADMIN","ROLE_USER"]
admin submits a wrong code
POST /mfa/otp code=000000 -> 401
GET /admin/panel -> 403
admin submits the right code
POST /mfa/otp code=246810 -> 200
GET /admin/panel -> 200
GET /whoami -> ["FACTOR_OTT","FACTOR_PASSWORD","ROLE_ADMIN","ROLE_USER"]
user (no ADMIN role) passes the one-time-code step too
GET /admin/panel -> 403
A factor is not a role. The last two lines of the output show a plainusercompleting the one-time-code step and still getting403on/admin/panel: the rule demandsROLE_ADMINand both factors. Also note thatOtpVerifierin this demo accepts the constant246810for everyone — it exists so the test is deterministic. Replace it with TOTP or a push approval before you ship anything.
Reference detail: how the multiFactor() rule is evaluated
AuthorizationManagerFactories.multiFactor() (7.1.2) returns a builder; requireFactors(String...) lists the authority names that must all be present, and .build() yields a factory with the usual hasRole(...), authenticated() and similar methods. In the test above its hasRole("ADMIN") demanded both factors as well as the role. I confirmed the shape with javap against the 7.1.2 jars: the builder also has when(Predicate<Authentication>) to apply the extra factors conditionally and requireFactor(Consumer<RequiredFactor.Builder>), where a RequiredFactor can carry a validity duration — useful for “re-prove the second factor every 15 minutes”. Each FactorGrantedAuthority records an issuedAt instant for that purpose. I did not exercise the duration option in this article’s tests, so treat that part as read from the API, not run.
There is also an @EnableMultiFactorAuthentication(authorities = ...) annotation for requiring factors globally, which this article does not use because a global rule would also demand the second factor on /user/**.
Going deeper
- Spring Security reference: Multi-Factor Authentication
- JWT Refresh Token Rotation in Spring Security 7 (With Reuse Detection) — another place where an extra proof has to be remembered across requests
7. What actually wires a provider in — and why a second bean breaks it silently
Most “Security 6 to 7” upgrade posts will tell you AuthenticationManager wiring changed. It mostly didn’t — the mechanism below has existed since Spring Security 4.1. In plain terms: every SecurityFilterChain gets its own small, initially empty authentication manager, and that small manager has one shared, application-wide manager as its parent. Calling .authenticationProvider(...) on a chain puts a provider in the small one. If you never call it, the chain relies on whatever ended up in the shared parent — and the shared parent is filled in automatically, but only under one condition.
Show the Security 7.1.2 source for both halves of that sentence
Per-chain manager and its parent, from HttpSecurityConfiguration.httpSecurity() (@Scope("prototype"), so each chain gets a fresh one), as it appears in spring-security-config-7.1.2-sources.jar:
AuthenticationManagerBuilder authenticationBuilder = new DefaultPasswordEncoderAuthenticationManagerBuilder(
this.objectPostProcessor, passwordEncoder);
authenticationBuilder.parentAuthenticationManager(authenticationManager());
authenticationBuilder.authenticationEventPublisher(getAuthenticationEventPublisher());
HttpSecurity http = new HttpSecurity(this.objectPostProcessor, authenticationBuilder, createSharedObjects());The shared parent is populated by InitializeAuthenticationProviderBeanManagerConfigurer (@since 4.1). The condition, quoted from the sources jar (spring-security-config-7.1.2-sources.jar):
if (auth.isConfigured()) {
return;
}
String[] beanNames = InitializeAuthenticationProviderBeanManagerConfigurer.this.context
.getBeanNamesForType(AuthenticationProvider.class);
if (beanNames.length == 0) {
return;
}
else if (beanNames.length > 1) {
this.logger.info(LogMessage.format("Found %s AuthenticationProvider beans, with names %s. "
+ "Global Authentication Manager will not be configured with AuthenticationProviders. "
+ "Consider publishing a single AuthenticationProvider bean, or wiring your Providers directly "
+ "using the DSL.", beanNames.length, Arrays.toString(beanNames)));
return;
}
AuthenticationProvider authenticationProvider = InitializeAuthenticationProviderBeanManagerConfigurer.this.context
.getBean(beanNames[0], AuthenticationProvider.class);
auth.authenticationProvider(authenticationProvider);Zero provider beans: nothing happens. Exactly one: it joins the shared parent. Two or more: the method logs one INFO line and returns, wiring neither.
That last branch is the trap. WiringTests.java starts a small application per row below; each chain never calls .authenticationProvider(...), posts admin/secret to each, and records the result (block 05):
Chain never calls .authenticationProvider(...); admin/secret posted to /login
one AuthenticationProvider bean -> 302 -> / InteractiveAuthenticationSuccessEvent
two AuthenticationProvider beans -> 302 -> /login?error AuthenticationFailureProviderNotFoundEvent
two beans, chain attaches CustomAuthProvider -> 302 -> / InteractiveAuthenticationSuccessEvent
With one provider bean the login works. Add a second bean — the second one here never even authenticates anyone — and the same request fails with AuthenticationFailureProviderNotFoundEvent. Attaching the provider to the chain explicitly fixes it, as the third line shows. The only trace at start-up is one INFO line (test-output file, block 05):
Found 2 AuthenticationProvider beans, with names [customAuthProvider, idleProvider]. Global Authentication Manager will not be configured with AuthenticationProviders. Consider publishing a single AuthenticationProvider bean, or wiring your Providers directly using the DSL.
The failure that produces no error. Add a secondAuthenticationProviderbean anywhere in the context — a second custom provider, a test fixture, a library you pulled in — and the auto-wiring backs off for both. Any chain relying on it now fails at request time withProviderNotFoundException, and in a browser that looks like an ordinary “wrong password” redirect to/login?error. The fix is the one this article uses throughout: attach providers explicitly with.authenticationProvider(...)on the specific chain.
What the hand-built AuthenticationManager bean from the old article really did
The 2025 article published a ProviderManager as an AuthenticationManager bean. The last scenarios of the same test (WiringTests.java) measure what such a bean does (block 05, continued):
A hand-built AuthenticationManager bean (what the 2025 article published):
one provider bean + manager bean(only mgr/x) admin/secret -> 302 -> / InteractiveAuthenticationSuccessEvent
one provider bean + manager bean(only mgr/x) mgr/x -> 302 -> /login?error AuthenticationFailureBadCredentialsEvent
two provider beans + manager bean listing both admin/secret -> 302 -> / InteractiveAuthenticationSuccessEvent
With one provider bean, the hand-built manager is ignored: admin/secret (the provider bean) works and mgr/x (only known to the manager bean) does not. The source explains it — AuthenticationConfiguration asks the global builder for a manager first and only falls back to an AuthenticationManager bean when the builder produced nothing (if (this.authenticationManager == null) { this.authenticationManager = getAuthenticationManagerBean(); }). With two provider beans the builder produces nothing, so the hand-built manager is used, and it rescues the login. So the old pattern was not harmful; it was redundant for one provider and a global workaround for several. Attaching providers to the chain is better because it is local — a manager bean is shared by every chain that does not configure its own.
Going deeper
- Change
TwoBeansExplicitAttachin WiringTests.java to see which chain each provider reaches. - Authentication Architecture: ProviderManager and its parent
8. Living alongside JWT in the same application
The question every real project eventually asks: what if /api/** needs to accept JWT bearer tokens issued by an authorization server, while everything else — an admin console, say — still authenticates through CustomAuthProvider? Add spring-boot-starter-security-oauth2-resource-server to the dependencies from section 2, then two SecurityFilterChain beans, ordered and scoped by securityMatcher() (MultiChainSecurityConfig.java):
package com.ankurm.authdemo.config;
import com.ankurm.authdemo.auth.CustomAuthProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@Profile("multichain")
public class MultiChainSecurityConfig {
@Bean
public CustomAuthProvider customAuthProvider() {
return new CustomAuthProvider();
}
// Chain 1: JWT-secured API. The bearer-token filter is authenticated by a
// JwtAuthenticationProvider that oauth2ResourceServer() builds internally --
// it never touches the shared AuthenticationManager, so it is unaffected by
// whatever AuthenticationProvider beans exist elsewhere in the context.
@Bean
@Order(1)
public SecurityFilterChain apiFilterChain(HttpSecurity http, JwtDecoder jwtDecoder) throws Exception {
http
.securityMatcher("/api/**")
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(jwtDecoder)))
.csrf(csrf -> csrf.disable());
return http.build();
}
// Chain 2: everything else, authenticated by CustomAuthProvider via form login.
// Attaching the provider explicitly -- rather than counting on it being the
// only AuthenticationProvider bean in the context -- keeps it scoped to this
// chain even if a second provider bean shows up later.
@Bean
@Order(2)
public SecurityFilterChain webFilterChain(HttpSecurity http) throws Exception {
http
.authenticationProvider(customAuthProvider())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults());
return http.build();
}
}
The left side is why bearer tokens and form-login credentials do not collide by accident: the JWT chain’s provider has a private manager and never asks the shared one. The right side is why they can collide the moment you add anything other than JWT to the API chain.
Both halves are tests. MultiChainTests.java exercises the configuration above (block 06), and BasicLeakTests.java adds httpBasic() to the API chain “just for testing” (block 07):
As documented: /api/** chain is JWT only, everything else uses CustomAuthProvider
GET /api/ping Bearer JWT -> 200
GET /api/ping no credentials -> 401
GET /api/ping Basic admin:secret -> 401
GET /admin/panel after form login admin/secret -> 200
apiFilterChain with .httpBasic(...) added "just for testing"
GET /api/ping Basic admin:secret -> 200
GET /api/ping Basic admin:wrong -> 401
In the first run, Basic credentials on the API get 401 — the chain only understands bearer tokens, and this is where a real 401 comes from. In the second, admin/secret suddenly authenticates against the JWT-only API, because httpBasic() uses the shared manager, which holds CustomAuthProvider. Enable a second mechanism on the API chain and decide deliberately which provider it should reach.
JwtDecoder is autowired rather than built in the config — set spring.security.oauth2.resourceserver.jwt.issuer-uri (or jwk-set-uri) and Boot supplies it. The tests substitute a mock, which is enough because they only check which chain answers. The JWT side has its own dense set of gotchas — token validation defaults, the bearer-scheme exception classes living in three different packages, and an RFC 9728 metadata filter that appears in the chain without you asking for it. That is a full article on its own: Spring Security 7.1 JWT Authentication: The Complete Guide covers it end to end, including a runnable companion repository.
Going deeper
- Spring Security 7.1 JWT Authentication: The Complete Guide
- RFC 9728 — OAuth 2.0 Protected Resource Metadata
9. The long tail
- Method security alongside
SecurityFilterChainrules.@PreAuthorizenow runs throughAuthorizationManager; there is noAccessDecisionManagerclass left inspring-security-core7.1.2 (I listed the jar to check), so pre-7.0 custom voters need to be ported. Covered end to end, with runnable code, in Method Security in Spring Security 7: @PreAuthorize, @PostAuthorize and the Proxy Traps — including the three ways an annotated method runs without the check firing at all. For the broader breaking-change list, see the Spring Security 6 to 7 Migration Guide and the Spring Framework 6 to 7 Migration Guide. - Hand-built
RequestMatchers. This article only ever passes strings to.requestMatchers(...), which Boot resolves through an auto-configuredPathPatternRequestMatcher.Builderwithout any code change. If you were constructingAntPathRequestMatcherorMvcRequestMatcherinstances directly: neither class exists inspring-security-web7.1.2 (checked by listing the jar), so that code will not compile. - Custom
hasPermission()checks. A provider decides who the user is; aPermissionEvaluatordecides what they may touch. See Spring Security hasPermission(): PermissionEvaluator and @EnableMethodSecurity. - Multiple custom providers, one chain. Attach each with its own
.authenticationProvider(...)call rather than adding a second bean and hoping — section 7 shows exactly why the second bean goes quiet, and section 5 shows the ordering rules. - The demo secrets.
admin/secret,user/passwordand the one-time code246810exist so the tests are deterministic. None of them belongs in a real application. - Remove
/whoamibefore shipping. It prints the caller’s authorities, which is useful while learning and an information leak in production.
Comparison: custom vs. built-in providers
When should you actually exert the effort to build what we just built?
| Feature | Built-in (DaoAuthenticationProvider) | Custom AuthenticationProvider |
|---|---|---|
| Data Source | JDBC, JPA, LDAP | Any (API, Legacy DB, File, RPC) |
| Complexity | Low (Configuration only) | Medium (Requires coding) |
| Flexibility | Limited to standard schemas | Infinite |
| Maintenance | Handled by Spring Team | Handled by You |
Should you even build one? If your credentials live in somethingUserDetailsServicecan already describe — a different table, a different column mapping — overrideUserDetailsServiceand keepDaoAuthenticationProvider. Less code, same guarantees, and you inherit every future Security patch for free. If you’re validating bearer tokens, use the resource server support, not a hand-rolled provider. If you only want a one-time-code login, check the built-in one-time-token support before writing your own. Write a realAuthenticationProviderwhen the input genuinely isn’t a username/password pair, or the verification step needs logicUserDetailsServicehas no way to express — a legacy RPC call, a hardware-token check, a rule that depends on more than “does this hash match.”
Conclusion
Implementing a custom authentication provider in Spring Security empowers you to bridge modern security frameworks with legacy or complex user stores. By adhering to the AuthenticationProvider contract — return a token, return null, or throw the exception whose routing you actually intend — and by attaching providers explicitly to the SecurityFilterChain, you keep a clean separation of concerns while solving difficult business requirements.
Next steps: download the project, run mvn test, and break things on purpose: reorder the providers, delete the saveContext line, add a third provider bean. Each of those changes is one of the failures above, and each has a test that will tell you which sentence of this article it contradicts.
Frequently Asked Questions
What is the difference between AuthenticationProvider and UserDetailsService?
UserDetailsService is a lighter interface used only to retrieve user data (username, password, authorities) from a database. The standard DaoAuthenticationProvider uses it. You implement AuthenticationProvider when you need to customize the actual verification logic (how passwords are checked) or if your user data isn’t in a database compatible with UserDetails.
Do I need to manually build a ProviderManager bean in Spring Security 7.1?
No. With one AuthenticationProvider bean, Spring wires it into the shared AuthenticationManager for you (a mechanism dating to Security 4.1), and a hand-built AuthenticationManager bean is ignored. With several provider beans, attach each to the chain with .authenticationProvider(...); a hand-built manager bean also works but is shared by every chain that does not configure its own. See section 7.
Can I have multiple Authentication Providers in Spring Security?
Yes. The ProviderManager asks them in order until one returns a token. A provider that returns null or throws BadCredentialsException hands over to the next one; an account-status exception such as LockedException stops the search. Wire them explicitly on the chain, because as soon as you have more than one AuthenticationProvider bean the automatic wiring in section 7 backs off for all of them.
Can I mix a custom AuthenticationProvider with JWT authentication in the same application?
Yes — define two SecurityFilterChain beans, scope each with .securityMatcher(...), and give each chain @Order. Section 8 has a working configuration, a test for it, and the one gotcha (leaking a second authentication mechanism onto the JWT chain) that catches people who skip the ordering.
How do I handle third-party API authentication failures in a custom provider?
If your custom provider calls an external API and that API is down, throw an AuthenticationServiceException. This signals a system error rather than a “Bad Credentials” error, allowing you to handle the failure gracefully (e.g., by showing a “Service Unavailable” page) instead of telling the user their password is wrong. Remember that the manager will still try the next provider after a plain AuthenticationServiceException; use InternalAuthenticationServiceException if the outage should end the attempt.
How do I add a second factor to a custom provider?
Grant a FactorGrantedAuthority from each provider (FACTOR_PASSWORD after the password check), add a second provider and token type for the one-time code that grants FACTOR_OTT, save the upgraded Authentication into the session, and require both factors with AuthorizationManagerFactories.multiFactor(). Section 6 has the complete, tested code.
Further Reading
- custom-auth-provider-demo.zip — the whole Maven project behind this article (9 tests), and the captured test output
- Spring Security 7.1 JWT Authentication: The Complete Guide — the resource-server side of section 8, with a runnable repository
- Method Security in Spring Security 7: @PreAuthorize, @PostAuthorize and the Proxy Traps — what happens to the
Authenticationthis article mints once a@PreAuthorizeexpression reads it - Spring Security 6 to 7 Migration Guide: Removed APIs, Moved Modules and What Breaks
- Spring Framework 6 to 7 Migration Guide — the full breaking-change list this article only touches where relevant
- JWT Refresh Token Rotation in Spring Security 7 (With Reuse Detection)
- Spring Security: Authentication Architecture (official reference)
- Spring Security: Multi-Factor Authentication (official reference)
- Spring Security: Migrating to 7.0 (official migration guide)
- RFC 9728 — OAuth 2.0 Protected Resource Metadata
No Comments yet!