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:

  1. A filter reads credentials from the request: BasicAuthenticationFilter from the Authorization header, UsernamePasswordAuthenticationFilter from a login form. It wraps them in an unauthenticated Authentication object, such as a UsernamePasswordAuthenticationToken.
  2. It passes that object to the AuthenticationManager. The usual implementation, ProviderManager, holds a list of AuthenticationProviders and asks each one in turn whether it supports this kind of token.
  3. The provider checks the credentials. For usernames and passwords this is DaoAuthenticationProvider: it loads the user through a UserDetailsService, checks the account flags, and compares the password with a PasswordEncoder.
  4. On success, the provider returns a new, authenticated Authentication holding the user and their authorities. The filter stores it in the SecurityContextHolder, and authorization can begin.
Extension points, from most to least common
InterfaceReplace it whenExample
UserDetailsServiceUsers live in your own database or serviceLoad a user by email with JDBC or JPA
UserDetailsCode needs more than a name and authoritiesYour AppUser with an id and tenant
PasswordEncoderStored hashes use another algorithmArgon2, or a legacy hash during migration
UserDetailsPasswordServiceOld hashes should be upgraded on loginRewrite {noop} or weak BCrypt values
AuthenticationProviderCredentials are not a username and password, or are checked elsewhereAPI keys, LDAP, a one-time code
A filterCredentials arrive in a place no built-in filter readsAn X-API-Key header

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:

Java
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());
            }
        }
    }
}
Output
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 ann returned an AppUser, the application's own class, so code later on can read its id, here 1, without another query.
  • ANN@example.com also worked, because the service lowercases the email before the query. Spring Security passes the name exactly as typed; case rules are up to your UserDetailsService.
  • A wrong password and an unknown user produced the same BadCredentialsException: Bad credentials. DaoAuthenticationProvider turns UsernameNotFoundException into BadCredentialsException, 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.
  • bob is disabled, so the right password gave DisabledException; cy is locked, so both the right and the wrong password gave LockedException. 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.
  • credentials kept: false: ProviderManager erases the password from the returned token after a successful login, so it does not stay in memory with the session.
  • The authorities contain FACTOR_PASSWORD as well as ROLE_USER. 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.

Implementing UserDetails directly on a JPA entity is common but mixes persistence and security; a small adapter class like AppUser, built from the row, keeps the two apart. In a Spring Boot application, declaring the UserDetailsService as a bean is enough: Boot's auto-configuration builds the DaoAuthenticationProvider and ProviderManager around it, and stops creating its default user.

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} value, the worst case, and logs in twice:

Java
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})");
    }
}
Output
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 upgradeEncoding reported that {noop} is not the current default, DaoAuthenticationProvider encoded the password again and called updatePassword. The stored value became {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 BCryptPasswordEncoder with a higher strength reports older, weaker hashes as needing an upgrade. In a Spring Boot application, a UserDetailsService bean that also implements UserDetailsPasswordService is picked up for this automatically. Since Spring Security 6.3, setCompromisedPasswordChecker can also reject passwords that appear in known data breaches; the bundled implementation calls the Have I Been Pwned API over the network, so it is not run here.

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 UserDetailsService. A provider of your own handles it, next to the password provider, in one ProviderManager. The four requests below are routed to different providers by their token type:

Java
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());
            }
        }
    }
}
Output
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 UsernamePasswordAuthenticationToken was handled by DaoAuthenticationProvider and authenticated ann.
  • The first ApiKeyToken was skipped by the password provider, whose supports returned false, and accepted by ApiKeyProvider, which returned a new token for billing-service with ROLE_SERVICE.
  • The unknown key reached the same provider and failed with unknown API key.
  • A token type that no provider supports caused ProviderNotFoundException, which is an AuthenticationException like the others.

A provider has three possible answers: return an authenticated token, throw an AuthenticationException to reject the credentials, or return null to say "not mine, ask the next one". ProviderManager stops at the first token returned. If a provider throws a BadCredentialsException, the manager keeps it and still asks the remaining providers, throwing it only when none succeeds. Account state exceptions such as LockedException and DisabledException stop the search at once. This is what lets a company directory and a local user table work side by side: an LDAP provider and a DaoAuthenticationProvider both handle username and password tokens, and the user is accepted by whichever one recognises the password.

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-Key header, no built-in filter does that, so this Spring Boot application adds a OncePerRequestFilter to the chain and calls the endpoint with no key, a wrong key and a valid one:

Java
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() : ""));
            }
        }
    }
}
Output
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 AuthorizationFilter as anonymous, and the entry point answered 401.
  • With an unknown key, the filter itself rejected the request with 401, without calling the controller.
  • With k-7f3a, the filter stored an authenticated token for billing-service in a new SecurityContext, the rule hasRole("SERVICE") passed, and the controller received it as its Authentication parameter.

Several details in this filter are deliberate:

  • Position: addFilterBefore(..., BasicAuthenticationFilter.class) places it with the other authentication filters, before AuthorizationFilter decides.
  • A new context: SecurityContextHolder.createEmptyContext() followed by setContext avoids changing a context object that other threads may share.
  • Not a bean: the filter is created with new. A filter declared as a @Bean 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 FilterRegistrationBean with setEnabled(false).
  • Stateless: SessionCreationPolicy.STATELESS and no CSRF, because a machine client sends the key on every request and never holds a session cookie.

For larger designs, Spring Security also has AuthenticationFilter, which takes an AuthenticationConverter and an AuthenticationManager, so the filter only converts the request and a provider does the checking, as in the previous section. Bearer tokens such as JWTs have built-in support, shown on the JWT and OAuth2 resource server pages.

Reacting to logins: events and lockout

ProviderManager can publish an event after every attempt, which is the place for audit logs and brute-force protection. This listener counts failed passwords and locks the account after three in a row; the six attempts below include a success in the middle to show the counter reset:

Java
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());
                }
            }
        }
    }
}
Output
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 AuthenticationFailureBadCredentialsEvent, and the counter reached 1.
  • The correct password then published AuthenticationSuccessEvent, and the listener cleared the counter.
  • Three wrong passwords in a row took it to 3 of 3, and the listener added ann to the locked set.
  • The last attempt used the correct password and still failed with LockedException, because the UserDetailsService now builds ann with accountLocked(true). No event line appears for it: a locked account maps to a different event class, AuthenticationFailureLockedEvent, which this listener ignores.

The events reach the listener only because the manager was given a DefaultAuthenticationEventPublisher; a manager without one publishes nothing. Spring Boot registers such a publisher, and wires it into the manager it builds, so a listener bean is all you need there. A real lockout keeps the counters in the database or a shared cache, not in memory, so that every server sees them, and unlocks after a timeout, because a permanent lock lets anyone shut a user out by guessing wrong three times.

Choosing where to plug in

Common requirements and the piece to write
RequirementWrite
Users in your own tableA UserDetailsService bean, returning your own UserDetails adapter
Login by email, case-insensitiveNormalise the name inside loadUserByUsername
Disabled, locked or expired accountsMap your columns to the isEnabled, isAccountNonLocked and related methods
Moving old password hashes to BCryptA {id} prefix on stored values plus UserDetailsPasswordService
API keys or another credential typeAn AuthenticationProvider and, if a header must be read, a filter
Company directory and local users togetherTwo providers in one ProviderManager
Audit logs and lockoutAn event listener for AbstractAuthenticationEvent
Tokens from an identity providerNo custom code: oauth2ResourceServer, see OAuth2 resource server

Write as little authentication code as you can: a UserDetailsService covers most applications, and every custom filter is security-critical code that needs its own tests. For the rest of the filter chain and URL rules, see Spring Security in Spring Boot; for permission checks after login, see method security.