Custom authentication in Spring Security: where your users and credentials plug in
Spring Security's login process is a chain of small interfaces: a manager that asks providers, a provider that loads a user and checks a password, and a filter that turns a request into a login attempt. Each one is a place to plug in your own code. This page builds each piece, from users stored in a database to an API key filter, and runs them against Spring Security 7.1.
Contents
How Spring Security authenticates a request
Authentication answers one question: who is making this request? Spring Security splits the answer into small interfaces, so that you can replace one part, such as where users are stored, and keep the rest:
- A filter reads credentials from the request:
from theBasicAuthenticationFilter header,Authorization from a login form. It wraps them in an unauthenticatedUsernamePasswordAuthenticationFilter object, such as aAuthentication .UsernamePasswordAuthenticationToken - It passes that object to the
. The usual implementation,AuthenticationManager , holds a list ofProviderManager s and asks each one in turn whether itAuthenticationProvider this kind of token.supports - The provider checks the credentials. For usernames and passwords this is
: it loads the user through aDaoAuthenticationProvider , checks the account flags, and compares the password with aUserDetailsService .PasswordEncoder - On success, the provider returns a new, authenticated
holding the user and their authorities. The filter stores it in theAuthentication , and authorization can begin.SecurityContextHolder
| Interface | Replace it when | Example |
|---|---|---|
UserDetailsService | Users live in your own database or service | Load a user by email with JDBC or JPA |
UserDetails | Code needs more than a name and authorities | Your AppUser |
PasswordEncoder | Stored hashes use another algorithm | Argon2, or a legacy hash during migration |
UserDetailsPasswordService | Old hashes should be upgraded on login | Rewrite {noop} |
AuthenticationProvider | Credentials are not a username and password, or are checked elsewhere | API keys, LDAP, a one-time code |
| A filter | Credentials arrive in a place no built-in filter reads | An X-API-Key |
The examples run Spring Security 7.1.2, the version in Spring Boot 4.1. The first three use the authentication classes directly with no web server, which shows each step clearly; the fourth is a Spring Boot web application.
Users from a database: UserDetailsService and UserDetails
Most applications keep users in their own table, with columns Spring Security knows nothing about. The program below stores three users in H2 (one active, one disabled, one locked) and tries seven logins that cover each outcome the provider can return:
import java.util.List;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
public class DatabaseUsers {
/** The application's own user type, exposed to Spring Security as UserDetails. */
static class AppUser implements UserDetails {
final long id;
final String email;
final String passwordHash;
final String role;
final boolean active;
final boolean locked;
AppUser(long id, String email, String passwordHash, String role,
boolean active, boolean locked) {
this.id = id;
this.email = email;
this.passwordHash = passwordHash;
this.role = role;
this.active = active;
this.locked = locked;
}
@Override
public String getUsername() {
return email;
}
@Override
public String getPassword() {
return passwordHash;
}
@Override
public List<GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority("ROLE_" + role));
}
@Override
public boolean isEnabled() {
return active;
}
@Override
public boolean isAccountNonLocked() {
return !locked;
}
}
static class JdbcUserService implements UserDetailsService {
private final JdbcTemplate jdbc;
JdbcUserService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public UserDetails loadUserByUsername(String email) {
try {
return jdbc.queryForObject(
"SELECT * FROM app_user WHERE email = ?",
(rs, n) -> new AppUser(rs.getLong("id"), rs.getString("email"),
rs.getString("password_hash"), rs.getString("role"),
rs.getBoolean("active"), rs.getBoolean("locked")),
email.toLowerCase());
} catch (EmptyResultDataAccessException e) {
throw new UsernameNotFoundException("no user " + email);
}
}
}
static List<String> names(Authentication auth) {
return auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
}
public static void main(String[] args) {
JdbcTemplate jdbc = new JdbcTemplate(
new DriverManagerDataSource("jdbc:h2:mem:users;DB_CLOSE_DELAY=-1"));
jdbc.execute("CREATE TABLE app_user (id BIGINT PRIMARY KEY, email VARCHAR(80) UNIQUE,"
+ " password_hash VARCHAR(100), role VARCHAR(20), active BOOLEAN,"
+ " locked BOOLEAN)");
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String hash = encoder.encode("s3cret-pw");
jdbc.update("INSERT INTO app_user VALUES (1, 'ann@example.com', ?, 'USER', TRUE, FALSE)",
hash);
jdbc.update("INSERT INTO app_user VALUES (2, 'bob@example.com', ?, 'USER', FALSE, FALSE)",
hash);
jdbc.update("INSERT INTO app_user VALUES (3, 'cy@example.com', ?, 'ADMIN', TRUE, TRUE)",
hash);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(
new JdbcUserService(jdbc));
provider.setPasswordEncoder(encoder);
AuthenticationManager manager = new ProviderManager(provider);
String[][] attempts = {
{"ann@example.com", "s3cret-pw"}, {"ANN@example.com", "s3cret-pw"},
{"ann@example.com", "wrong"}, {"nobody@example.com", "s3cret-pw"},
{"bob@example.com", "s3cret-pw"}, {"cy@example.com", "s3cret-pw"},
{"cy@example.com", "wrong"},
};
for (String[] a : attempts) {
String label = String.format("%-19s / %-9s -> ", a[0], a[1]);
try {
Authentication result = manager.authenticate(
UsernamePasswordAuthenticationToken.unauthenticated(a[0], a[1]));
AppUser user = (AppUser) result.getPrincipal();
System.out.println(label + "OK, id " + user.id + ", " + names(result)
+ ", credentials kept: " + (result.getCredentials() != null));
} catch (AuthenticationException e) {
System.out.println(label + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
}
ann@example.com / s3cret-pw -> OK, id 1, [ROLE_USER, FACTOR_PASSWORD], credentials kept: false
ANN@example.com / s3cret-pw -> OK, id 1, [ROLE_USER, FACTOR_PASSWORD], credentials kept: false
ann@example.com / wrong -> BadCredentialsException: Bad credentials
nobody@example.com / s3cret-pw -> BadCredentialsException: Bad credentials
bob@example.com / s3cret-pw -> DisabledException: User is disabled
cy@example.com / s3cret-pw -> LockedException: User account is locked
cy@example.com / wrong -> LockedException: User account is locked
- The correct password for
returned anann , the application's own class, so code later on can read itsAppUser , here 1, without another query.id also worked, because the service lowercases the email before the query. Spring Security passes the name exactly as typed; case rules are up to yourANN@example.com .UserDetailsService- A wrong password and an unknown user produced the same
.BadCredentialsException: Bad credentials turnsDaoAuthenticationProvider intoUsernameNotFoundException , so an attacker cannot use the login form to find out which emails have accounts. For unknown users it also hashes the given password anyway, so that both cases take about the same time.BadCredentialsException is disabled, so the right password gavebob ;DisabledException is locked, so both the right and the wrong password gavecy . These account checks run before the password check, which means a locked account reveals that it exists. Show a general message to the user whatever the exception.LockedException :credentials kept: false erases the password from the returned token after a successful login, so it does not stay in memory with the session.ProviderManager- The authorities contain
as well asFACTOR_PASSWORD . Spring Security 7 added multi-factor authentication, and each provider records the factor it checked, so that rules can later require, for example, both a password and a one-time code.ROLE_USER
Implementing UserDetailsAppUserUserDetailsServiceDaoAuthenticationProviderProviderManageruser
Upgrading stored passwords on login
Password hashes cannot be converted in a batch job, because the job never sees the plain passwords. The user's next login is the only moment when the plain password is available, and Spring Security can rewrite the hash then. This program starts with a plain-text {noop}
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
public class PasswordUpgrade {
/** Stands in for a users table: username to stored password value. */
static class UserStore implements UserDetailsService, UserDetailsPasswordService {
final Map<String, String> passwords = new HashMap<>();
@Override
public UserDetails loadUserByUsername(String username) {
String stored = passwords.get(username);
if (stored == null) {
throw new UsernameNotFoundException(username);
}
return User.withUsername(username).password(stored).roles("USER").build();
}
@Override
public UserDetails updatePassword(UserDetails user, String newEncodedPassword) {
System.out.println(" updatePassword called for " + user.getUsername());
passwords.put(user.getUsername(), newEncodedPassword);
return User.withUserDetails(user).password(newEncodedPassword).build();
}
}
static String show(String stored) {
return stored.length() > 20 ? stored.substring(0, 15) + "..." : stored;
}
public static void main(String[] args) {
UserStore store = new UserStore();
store.passwords.put("ann", "{noop}plain-old");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(store);
provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
provider.setUserDetailsPasswordService(store);
ProviderManager manager = new ProviderManager(provider);
System.out.println("Stored before: ann = " + show(store.passwords.get("ann")));
System.out.println("Login 1 as ann:");
manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(
"ann", "plain-old"));
System.out.println("Stored after : ann = " + show(store.passwords.get("ann")));
System.out.println("Login 2 as ann:");
manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(
"ann", "plain-old"));
System.out.println(" (no update: the value is already {bcrypt})");
}
}
Stored before: ann = {noop}plain-old
Login 1 as ann:
updatePassword called for ann
Stored after : ann = {bcrypt}$2a$10$...
Login 2 as ann:
(no update: the value is already {bcrypt})
- Before the first login, the stored value was
.{noop}plain-old - The login succeeded, and because
reported thatupgradeEncoding is not the current default,{noop} encoded the password again and calledDaoAuthenticationProvider . The stored value becameupdatePassword .{bcrypt}$2a$10$... - The second login made no call: the value already used the current encoder and strength.
The same mechanism handles raising the BCrypt strength later: a BCryptPasswordEncoderUserDetailsServiceUserDetailsPasswordServicesetCompromisedPasswordChecker
A custom AuthenticationProvider
Not every credential is a username and password. A machine client may send an API key, and checking it has nothing to do with a UserDetailsServiceProviderManager
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
public class TwoProviders {
/** A credential type of our own: an API key sent by a machine client. */
static class ApiKeyToken extends AbstractAuthenticationToken {
private final String key;
private final String client;
ApiKeyToken(String key) { // before authentication
super((Collection<? extends GrantedAuthority>) null);
this.key = key;
this.client = null;
}
ApiKeyToken(String client, Collection<? extends GrantedAuthority> authorities) {
super(authorities); // after authentication
this.key = null;
this.client = client;
setAuthenticated(true);
}
@Override
public Object getCredentials() {
return key;
}
@Override
public Object getPrincipal() {
return client;
}
}
static class ApiKeyProvider implements AuthenticationProvider {
private final Map<String, String> keys = Map.of("k-7f3a", "billing-service");
@Override
public Authentication authenticate(Authentication authentication) {
String client = keys.get((String) authentication.getCredentials());
if (client == null) {
throw new BadCredentialsException("unknown API key");
}
return new ApiKeyToken(client, AuthorityUtils.createAuthorityList("ROLE_SERVICE"));
}
@Override
public boolean supports(Class<?> type) {
return ApiKeyToken.class.isAssignableFrom(type);
}
}
static List<String> names(Authentication auth) {
return auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
}
public static void main(String[] args) {
DaoAuthenticationProvider passwords = new DaoAuthenticationProvider(
new InMemoryUserDetailsManager(User.withUsername("ann")
.password("{noop}pw").roles("USER").build()));
ProviderManager manager = new ProviderManager(List.of(passwords, new ApiKeyProvider()));
Authentication[] requests = {
UsernamePasswordAuthenticationToken.unauthenticated("ann", "pw"),
new ApiKeyToken("k-7f3a"),
new ApiKeyToken("k-0000"),
new AbstractAuthenticationToken((Collection<? extends GrantedAuthority>) null) {
@Override
public Object getCredentials() {
return "?";
}
@Override
public Object getPrincipal() {
return "?";
}
},
};
for (Authentication request : requests) {
String type = request.getClass().getSimpleName().isEmpty()
? "an unsupported token" : request.getClass().getSimpleName();
try {
Authentication result = manager.authenticate(request);
System.out.println(type + " -> " + result.getName() + " "
+ names(result) + ", as "
+ result.getClass().getSimpleName());
} catch (AuthenticationException e) {
System.out.println(type + " -> " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
}
}
}
UsernamePasswordAuthenticationToken -> ann [ROLE_USER, FACTOR_PASSWORD], as UsernamePasswordAuthenticationToken
ApiKeyToken -> billing-service [ROLE_SERVICE], as ApiKeyToken
ApiKeyToken -> BadCredentialsException: unknown API key
an unsupported token -> ProviderNotFoundException: No AuthenticationProvider found for TwoProviders$1
- The
was handled byUsernamePasswordAuthenticationToken and authenticatedDaoAuthenticationProvider .ann - The first
was skipped by the password provider, whoseApiKeyToken returned false, and accepted bysupports , which returned a new token forApiKeyProvider withbilling-service .ROLE_SERVICE - The unknown key reached the same provider and failed with
.unknown API key - A token type that no provider supports caused
, which is anProviderNotFoundException like the others.AuthenticationException
A provider has three possible answers: return an authenticated token, throw an AuthenticationExceptionnullProviderManagerBadCredentialsExceptionLockedExceptionDisabledExceptionDaoAuthenticationProvider
Reading credentials from the request: a custom filter
A provider only checks credentials; something must first take them out of the request. For an X-API-KeyOncePerRequestFilter
package demo.auth.apikey;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.OncePerRequestFilter;
public class ApiKeyFilter {
/** Reads X-API-Key, and on a known key puts an Authentication into the context. */
static class ApiKeyAuthenticationFilter extends OncePerRequestFilter {
private final Map<String, String> keys = Map.of("k-7f3a", "billing-service");
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String key = request.getHeader("X-API-Key");
if (key != null) {
String client = keys.get(key);
if (client == null) {
SecurityContextHolder.clearContext();
response.sendError(401, new BadCredentialsException("bad key").getMessage());
return;
}
Authentication auth = UsernamePasswordAuthenticationToken.authenticated(
client, null, AuthorityUtils.createAuthorityList("ROLE_SERVICE"));
var context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(auth);
SecurityContextHolder.setContext(context);
}
chain.doFilter(request, response);
}
}
@RestController
static class InvoiceController {
@GetMapping("/api/invoices")
String invoices(Authentication caller) {
return "invoices for " + caller.getName() + " " + caller.getAuthorities();
}
}
@Configuration
@EnableAutoConfiguration
@Import(InvoiceController.class)
static class App {
@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().hasRole("SERVICE"))
.addFilterBefore(new ApiKeyAuthenticationFilter(),
BasicAuthenticationFilter.class)
.sessionManagement(s -> s.sessionCreationPolicy(
SessionCreationPolicy.STATELESS))
.exceptionHandling(e -> e.authenticationEntryPoint(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.csrf(csrf -> csrf.disable());
return http.build();
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(App.class);
app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
"logging.level.root", "WARN", "spring.security.user.password", "unused"));
try (ConfigurableApplicationContext context = app.run()) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
for (String key : new String[] {null, "k-0000", "k-7f3a"}) {
HttpRequest.Builder request = HttpRequest.newBuilder(
URI.create(base + "/api/invoices"));
if (key != null) {
request.header("X-API-Key", key);
}
HttpResponse<String> r = HttpClient.newHttpClient()
.send(request.build(), HttpResponse.BodyHandlers.ofString());
System.out.println("X-API-Key " + key + " -> " + r.statusCode()
+ (r.statusCode() == 200 ? " " + r.body() : ""));
}
}
}
}
X-API-Key null -> 401
X-API-Key k-0000 -> 401
X-API-Key k-7f3a -> 200 invoices for billing-service [ROLE_SERVICE]
- With no key, the filter did nothing, the request reached
as anonymous, and the entry point answered 401.AuthorizationFilter - With an unknown key, the filter itself rejected the request with 401, without calling the controller.
- With
, the filter stored an authenticated token fork-7f3a in a newbilling-service , the ruleSecurityContext passed, and the controller received it as itshasRole("SERVICE") parameter.Authentication
Several details in this filter are deliberate:
- Position:
places it with the other authentication filters, beforeaddFilterBefore(..., BasicAuthenticationFilter.class) decides.AuthorizationFilter - A new context:
followed bySecurityContextHolder.createEmptyContext() avoids changing a context object that other threads may share.setContext - Not a bean: the filter is created with
. A filter declared as anew is also registered by Spring Boot as an ordinary servlet filter, so it would run twice, once outside the security chain; if it must be a bean, add a@Bean withFilterRegistrationBean .setEnabled(false) - Stateless:
and no CSRF, because a machine client sends the key on every request and never holds a session cookie.SessionCreationPolicy.STATELESS
For larger designs, Spring Security also has AuthenticationFilterAuthenticationConverterAuthenticationManager
Reacting to logins: events and lockout
ProviderManager
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class LoginLockout {
static class Attempts implements ApplicationListener<AbstractAuthenticationEvent> {
static final int LIMIT = 3;
final Map<String, Integer> failures = new HashMap<>();
final Set<String> locked = new HashSet<>();
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
String user = event.getAuthentication().getName();
if (event instanceof AuthenticationFailureBadCredentialsEvent) {
int count = failures.merge(user, 1, Integer::sum);
System.out.println(" event: bad credentials for " + user + " (" + count
+ " of " + LIMIT + ")");
if (count >= LIMIT) {
locked.add(user);
}
} else if (event instanceof AuthenticationSuccessEvent) {
System.out.println(" event: success for " + user + ", counter reset");
failures.remove(user);
}
}
}
@Configuration
static class Config {
@Bean
Attempts attempts() {
return new Attempts();
}
@Bean
UserDetailsService users(Attempts attempts) {
return username -> {
if (!username.equals("ann")) {
throw new UsernameNotFoundException(username);
}
UserDetails ann = User.withUsername("ann").password("{noop}right")
.roles("USER").accountLocked(attempts.locked.contains("ann")).build();
return ann;
};
}
@Bean
AuthenticationEventPublisher eventPublisher(
ApplicationEventPublisher publisher) {
return new DefaultAuthenticationEventPublisher(publisher);
}
@Bean
AuthenticationManager authenticationManager(UserDetailsService users,
AuthenticationEventPublisher events) {
ProviderManager manager = new ProviderManager(new DaoAuthenticationProvider(users));
manager.setAuthenticationEventPublisher(events);
return manager;
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
AuthenticationManager manager = context.getBean(AuthenticationManager.class);
String[] passwords = {"wrong", "right", "wrong", "wrong", "wrong", "right"};
for (String password : passwords) {
System.out.println("ann / " + password + ":");
try {
manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(
"ann", password));
System.out.println(" logged in");
} catch (AuthenticationException e) {
System.out.println(" " + e.getClass().getSimpleName());
}
}
}
}
}
ann / wrong:
event: bad credentials for ann (1 of 3)
BadCredentialsException
ann / right:
event: success for ann, counter reset
logged in
ann / wrong:
event: bad credentials for ann (1 of 3)
BadCredentialsException
ann / wrong:
event: bad credentials for ann (2 of 3)
BadCredentialsException
ann / wrong:
event: bad credentials for ann (3 of 3)
BadCredentialsException
ann / right:
LockedException
- The first wrong password published
, and the counter reached 1.AuthenticationFailureBadCredentialsEvent - The correct password then published
, and the listener cleared the counter.AuthenticationSuccessEvent - Three wrong passwords in a row took it to 3 of 3, and the listener added
to the locked set.ann - The last attempt used the correct password and still failed with
, because theLockedException now buildsUserDetailsService withann . No event line appears for it: a locked account maps to a different event class,accountLocked(true) , which this listener ignores.AuthenticationFailureLockedEvent
The events reach the listener only because the manager was given a DefaultAuthenticationEventPublisher
Choosing where to plug in
| Requirement | Write |
|---|---|
| Users in your own table | A UserDetailsServiceUserDetails |
| Login by email, case-insensitive | Normalise the name inside loadUserByUsername |
| Disabled, locked or expired accounts | Map your columns to the isEnabledisAccountNonLocked |
| Moving old password hashes to BCrypt | A {id}UserDetailsPasswordService |
| API keys or another credential type | An AuthenticationProvider |
| Company directory and local users together | Two providers in one ProviderManager |
| Audit logs and lockout | An event listener for AbstractAuthenticationEvent |
| Tokens from an identity provider | No custom code: oauth2ResourceServer |
Write as little authentication code as you can: a UserDetailsService