or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication-filters.mdauthorization.mdcsrf-protection.mdfilter-chain.mdfirewall.mdindex.mdlogout.mdreactive-security.mdrequest-matching.mdsaved-requests.mdsecurity-context.mdsecurity-headers.mdservlet-integration.mdsession-management.md
tile.json

authentication-filters.mddocs/

Authentication Filters

Authentication filters handle various authentication mechanisms including form login, HTTP Basic, remember-me, one-time tokens, and pre-authentication.

Key Information for Agents

Required Dependencies:

  • spring-security-web (this package)
  • spring-security-core is required (provides AuthenticationManager, Authentication, AuthenticationException)
  • spring-security-config is required for HttpSecurity DSL configuration
  • UserDetailsService required for remember-me and form login (from spring-security-core)
  • DataSource required for persistent remember-me tokens (JdbcTokenRepositoryImpl)
  • For OTT: spring-security-ott module required (OneTimeTokenService)

Default Behaviors:

  • Form login: Default URL /login (POST), username parameter "username", password parameter "password"
  • UsernamePasswordAuthenticationFilter: postOnly=true (only processes POST requests)
  • AuthenticationFilter: Requires RequestMatcher to determine which requests to process
  • Success handler: SavedRequestAwareAuthenticationSuccessHandler (uses RequestCache for redirect)
  • Failure handler: SimpleUrlAuthenticationFailureHandler (redirects to failure URL)
  • Remember-me: Default cookie name "remember-me", token validity 1209600 seconds (2 weeks)
  • Basic authentication: Realm name must be set (default: empty, throws exception)
  • Anonymous authentication: Default principal "anonymousUser", key required for token generation
  • Session authentication strategy: Executes during authentication (after successful authentication)
  • continueChainBeforeSuccessfulAuthentication=false (filter chain stops after authentication by default)

Threading Model:

  • All authentication filters execute on servlet container thread (synchronous)
  • AuthenticationManager.authenticate() may block (depends on provider implementation)
  • Remember-me auto-login executes before authentication filters (in RememberMeAuthenticationFilter)
  • Session authentication strategies execute synchronously during authentication
  • Authentication success/failure handlers execute in same thread as filter
  • Multiple authentication converters: Evaluated in order until one returns non-null
  • Pre-authentication filters: Execute before form login filters (order in filter chain matters)

Lifecycle:

  • Authentication filters implement OncePerRequestFilter or GenericFilterBean (Spring lifecycle aware)
  • afterPropertiesSet() validates required dependencies (AuthenticationManager, etc.)
  • Remember-me services: autoLogin() called on every request (if no authentication present)
  • Remember-me cookie: Created on successful authentication (if parameter present or alwaysRemember=true)
  • Session authentication strategy: onAuthentication() called after successful authentication
  • Authentication details source: Creates details object for each authentication attempt
  • Pre-authentication filters: Execute before authentication filters in filter chain

Exceptions:

  • BadCredentialsException - Invalid username/password
  • AccountExpiredException - User account has expired
  • CredentialsExpiredException - User credentials have expired
  • DisabledException - User account is disabled
  • LockedException - User account is locked
  • RememberMeAuthenticationException - Remember-me authentication failures (CookieTheftException, InvalidCookieException)
  • NonceExpiredException - Digest authentication nonce expired
  • AuthenticationServiceException - Authentication service failures (wrapped exceptions)
  • ServletException, IOException - Servlet API exceptions

Edge Cases:

  • Multiple authentication filters: Order matters, first matching filter processes request
  • AuthenticationConverter returns null: No authentication attempt made (filter chain continues)
  • Remember-me without session: Requires cookie-based token repository (not session-based)
  • Persistent remember-me: Token series changes on each use (prevents token reuse)
  • Cookie theft detection: Series mismatch triggers CookieTheftException (all user tokens invalidated)
  • Pre-authentication: Must set exceptionIfHeaderMissing=false if header may be absent
  • X.509 authentication: Requires HTTPS and client certificate configuration in servlet container
  • Switch user: Original authentication stored in SwitchUserGrantedAuthority (can retrieve via getSource())
  • Anonymous authentication: Only created if no existing authentication (doesn't override existing auth)
  • MFA support: setMfaEnabled(true) allows multi-factor authentication flows
  • continueChainBeforeSuccessfulAuthentication=true: Filter chain continues after authentication (rare use case)
  • Authentication details: Created for each authentication attempt (includes IP address, session ID)
  • Delegating converters: First converter returning non-null wins (subsequent converters not called)

Core Authentication Infrastructure

AuthenticationFilter

Generic authentication filter that uses AuthenticationConverter and AuthenticationManager.

package org.springframework.security.web.authentication;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

public class AuthenticationFilter extends OncePerRequestFilter {
    /**
     * Creates an authentication filter.
     *
     * @param authenticationManager the authentication manager
     * @param authenticationConverter converts requests to Authentication
     */
    public AuthenticationFilter(AuthenticationManager authenticationManager,
                                 AuthenticationConverter authenticationConverter);
    
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException;
    
    public RequestMatcher getRequestMatcher();
    
    public void setRequestMatcher(RequestMatcher requestMatcher);
    
    public AuthenticationConverter getAuthenticationConverter();
    
    public void setAuthenticationConverter(AuthenticationConverter authenticationConverter);
    
    public AuthenticationSuccessHandler getSuccessHandler();
    
    public void setSuccessHandler(AuthenticationSuccessHandler successHandler);
    
    public AuthenticationFailureHandler getFailureHandler();
    
    public void setFailureHandler(AuthenticationFailureHandler failureHandler);
    
    /**
     * Enables multi-factor authentication support.
     */
    public void setMfaEnabled(boolean mfaEnabled);
}

AuthenticationConverter

Strategy for converting HttpServletRequest to Authentication.

package org.springframework.security.web.authentication;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;

public interface AuthenticationConverter {
    /**
     * Converts the request to an Authentication for processing.
     * Returns null if no authentication attempt should be made.
     *
     * @param request the HttpServletRequest
     * @return Authentication or null
     */
    Authentication convert(HttpServletRequest request);
}

DelegatingAuthenticationConverter

Delegates to multiple AuthenticationConverter implementations in order.

package org.springframework.security.web.authentication;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

import org.springframework.security.core.Authentication;

public class DelegatingAuthenticationConverter implements AuthenticationConverter {
    /**
     * Creates a delegating converter with the given converters.
     *
     * @param converters the list of authentication converters
     * @since 5.2
     */
    public DelegatingAuthenticationConverter(List<AuthenticationConverter> converters);

    /**
     * Attempts to convert using each converter in order until one returns a non-null result.
     */
    public Authentication convert(HttpServletRequest request);
}

AbstractAuthenticationProcessingFilter

Base class for authentication filters that process authentication requests.

package org.springframework.security.web.authentication;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.GenericFilterBean;

public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean {
    /**
     * Creates a filter with the given authentication manager and URL pattern.
     *
     * @param defaultFilterProcessesUrl the URL pattern to process
     */
    protected AbstractAuthenticationProcessingFilter(String defaultFilterProcessesUrl);

    /**
     * Creates a filter with the given authentication manager and request matcher.
     *
     * @param requiresAuthenticationRequestMatcher the request matcher
     */
    protected AbstractAuthenticationProcessingFilter(RequestMatcher requiresAuthenticationRequestMatcher);

    /**
     * Creates a filter with authentication manager and request matcher.
     *
     * @param requiresAuthenticationRequestMatcher the request matcher
     * @param authenticationManager the authentication manager
     */
    protected AbstractAuthenticationProcessingFilter(RequestMatcher requiresAuthenticationRequestMatcher,
                                                       AuthenticationManager authenticationManager);

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;

    /**
     * Performs the actual authentication. Must be implemented by subclasses.
     *
     * @param request the HTTP request
     * @param response the HTTP response
     * @return the authenticated user token
     * @throws AuthenticationException if authentication fails
     */
    public abstract Authentication attemptAuthentication(HttpServletRequest request,
                                                          HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException;

    /**
     * Sets the authentication manager.
     */
    public void setAuthenticationManager(AuthenticationManager authenticationManager);

    /**
     * Sets the success handler.
     */
    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler);

    /**
     * Sets the failure handler.
     */
    public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler);

    /**
     * Sets the session authentication strategy.
     */
    public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy);

    /**
     * Sets whether to continue the filter chain after successful authentication.
     * Default: false (filter chain stops after authentication).
     */
    public void setContinueChainBeforeSuccessfulAuthentication(boolean continueChainBeforeSuccessfulAuthentication);

    /**
     * Sets the authentication details source.
     */
    public void setAuthenticationDetailsSource(
            AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource);

    /**
     * Sets the RememberMeServices.
     */
    public void setRememberMeServices(RememberMeServices rememberMeServices);

    /**
     * Sets the SecurityContextRepository.
     */
    public void setSecurityContextRepository(SecurityContextRepository securityContextRepository);

    /**
     * Sets the SecurityContextHolderStrategy.
     */
    public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);

    public void afterPropertiesSet();
}

AuthenticationSuccessHandler

Strategy for handling successful authentication.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.Authentication;

public interface AuthenticationSuccessHandler {
    /**
     * Called when authentication succeeds.
     *
     * @param request the request
     * @param response the response
     * @param authentication the authenticated user
     */
    void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                  Authentication authentication) throws IOException, ServletException;
}

AuthenticationFailureHandler

Strategy for handling failed authentication.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;

public interface AuthenticationFailureHandler {
    /**
     * Called when authentication fails.
     *
     * @param request the request
     * @param response the response
     * @param exception the authentication exception
     */
    void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                  AuthenticationException exception) throws IOException, ServletException;
}

Authentication Entry Points

LoginUrlAuthenticationEntryPoint

Redirects users to a login form when authentication is required.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.PortMapper;

public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * Creates an entry point with the login form URL.
     *
     * @param loginFormUrl the URL of the login form
     */
    public LoginUrlAuthenticationEntryPoint(String loginFormUrl);

    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException;

    public void afterPropertiesSet();

    /**
     * Gets the login form URL.
     */
    public String getLoginFormUrl();

    /**
     * Forces HTTPS for the redirect.
     */
    public void setForceHttps(boolean forceHttps);

    /**
     * Sets the port mapper for HTTP/HTTPS port mapping.
     */
    public void setPortMapper(PortMapper portMapper);

    /**
     * Uses server-side forward instead of redirect.
     */
    public void setUseForward(boolean useForward);

    /**
     * Favors relative URIs over absolute URIs.
     */
    public void setFavorRelativeUris(boolean favorRelativeUris);
}

DelegatingAuthenticationEntryPoint

Selects an AuthenticationEntryPoint based on RequestMatcher evaluation.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.RequestMatcher;

public class DelegatingAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * Creates a delegating entry point.
     */
    public DelegatingAuthenticationEntryPoint(
            LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints);

    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException;

    /**
     * Sets the default entry point when no matchers match.
     */
    public void setDefaultEntryPoint(AuthenticationEntryPoint defaultEntryPoint);

    public void afterPropertiesSet();

    /**
     * Returns a builder for constructing the entry point.
     */
    public static Builder builder();

    public static final class Builder {
        /**
         * Sets the default entry point.
         */
        public Builder defaultEntryPoint(AuthenticationEntryPoint defaultEntryPoint);

        /**
         * Adds an entry point for matching requests.
         */
        public Builder addEntryPointFor(AuthenticationEntryPoint entryPoint, RequestMatcher requestMatcher);

        public DelegatingAuthenticationEntryPoint build();
    }
}

Http403ForbiddenEntryPoint

Returns HTTP 403 Forbidden status for authentication failures.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public final class Http403ForbiddenEntryPoint implements AuthenticationEntryPoint {
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException;
}

HttpStatusEntryPoint

Returns a configurable HTTP status code for authentication failures.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public final class HttpStatusEntryPoint implements AuthenticationEntryPoint {
    /**
     * Creates an entry point that returns the specified HTTP status.
     *
     * @param httpStatus the HTTP status to return
     */
    public HttpStatusEntryPoint(HttpStatus httpStatus);

    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException;
}

NoOpAuthenticationEntryPoint

An AuthenticationEntryPoint that does nothing.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public final class NoOpAuthenticationEntryPoint implements AuthenticationEntryPoint {
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException;
}

Form-Based Authentication

UsernamePasswordAuthenticationFilter

Processes username/password authentication form submissions.

package org.springframework.security.web.authentication;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    
    /**
     * Creates a filter with default settings (POST /login).
     */
    public UsernamePasswordAuthenticationFilter();
    
    /**
     * Creates a filter with the given authentication manager.
     */
    public UsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager);
    
    /**
     * Performs authentication from username and password parameters.
     */
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException;
    
    /**
     * Sets the request parameter name for username (default: "username").
     */
    public void setUsernameParameter(String usernameParameter);
    
    /**
     * Sets the request parameter name for password (default: "password").
     */
    public void setPasswordParameter(String passwordParameter);
    
    /**
     * Sets whether to only process POST requests (default: true).
     */
    public void setPostOnly(boolean postOnly);
    
    public final String getUsernameParameter();
    
    public final String getPasswordParameter();
    
    protected String obtainUsername(HttpServletRequest request);
    
    protected String obtainPassword(HttpServletRequest request);
}

Authentication Success/Failure Handlers

AbstractAuthenticationTargetUrlRequestHandler

Base class for handlers that redirect to a target URL.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.web.RedirectStrategy;

public abstract class AbstractAuthenticationTargetUrlRequestHandler {
    protected AbstractAuthenticationTargetUrlRequestHandler();

    /**
     * Performs the redirect or forward to the target URL.
     *
     * @param request the request
     * @param response the response
     * @param targetUrl the target URL
     */
    protected void handle(HttpServletRequest request, HttpServletResponse response, String targetUrl)
            throws IOException, ServletException;

    /**
     * Builds the target URL for redirection.
     *
     * @param request the request
     * @param response the response
     * @return the target URL
     */
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response);

    /**
     * Sets the default target URL.
     */
    public void setDefaultTargetUrl(String defaultTargetUrl);

    protected String getDefaultTargetUrl();

    /**
     * Sets whether to always use the default target URL.
     */
    public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl);

    protected boolean isAlwaysUseDefaultTargetUrl();

    /**
     * Sets the parameter name for the target URL.
     */
    public void setTargetUrlParameter(String targetUrlParameter);

    protected String getTargetUrlParameter();

    /**
     * Sets the redirect strategy.
     */
    public void setRedirectStrategy(RedirectStrategy redirectStrategy);

    protected RedirectStrategy getRedirectStrategy();
}

SimpleUrlAuthenticationSuccessHandler

Redirects or forwards to a configured URL on authentication success.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.RedirectStrategy;

public class SimpleUrlAuthenticationSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
        implements AuthenticationSuccessHandler {
    public SimpleUrlAuthenticationSuccessHandler();

    /**
     * Creates a handler with the specified target URL.
     */
    public SimpleUrlAuthenticationSuccessHandler(String defaultTargetUrl);

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException;

    public void setDefaultTargetUrl(String defaultTargetUrl);

    public String getDefaultTargetUrl();

    public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl);

    public void setTargetUrlParameter(String targetUrlParameter);

    public void setUseReferer(boolean useReferer);

    public void setRedirectStrategy(RedirectStrategy redirectStrategy);
}

SavedRequestAwareAuthenticationSuccessHandler

Uses saved request from RequestCache to redirect after authentication.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.savedrequest.RequestCache;

public class SavedRequestAwareAuthenticationSuccessHandler 
        extends SimpleUrlAuthenticationSuccessHandler {
    
    public SavedRequestAwareAuthenticationSuccessHandler();
    
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException;
    
    /**
     * Sets the RequestCache for retrieving saved requests.
     */
    public void setRequestCache(RequestCache requestCache);
}

ForwardAuthenticationSuccessHandler

Forwards to a target URL instead of redirecting.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.Authentication;

public class ForwardAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    /**
     * Creates a handler that forwards to the specified URL.
     */
    public ForwardAuthenticationSuccessHandler(String forwardUrl);

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException;
}

HttpMessageConverterAuthenticationSuccessHandler

Uses HttpMessageConverter to write authentication response.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.function.Function;

import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.core.Authentication;

public class HttpMessageConverterAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    /**
     * Creates a handler with default JSON message converter.
     *
     * @since 6.4
     */
    public HttpMessageConverterAuthenticationSuccessHandler();

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException;

    /**
     * Sets the function to extract the response body from Authentication.
     */
    public void setAuthenticationConverter(Function<Authentication, ?> authenticationConverter);

    /**
     * Sets the HTTP message converter.
     */
    public void setHttpMessageConverter(HttpMessageConverter<?> httpMessageConverter);
}

SimpleUrlAuthenticationFailureHandler

Redirects to a failure URL on authentication failure.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.RedirectStrategy;

public class SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {
    public SimpleUrlAuthenticationFailureHandler();
    
    /**
     * Creates a handler with the specified failure URL.
     */
    public SimpleUrlAuthenticationFailureHandler(String defaultFailureUrl);
    
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException;
    
    /**
     * Sets the URL to redirect to on failure.
     */
    public void setDefaultFailureUrl(String defaultFailureUrl);
    
    /**
     * Uses forward instead of redirect.
     */
    public void setUseForward(boolean forwardToDestination);
    
    public void setRedirectStrategy(RedirectStrategy redirectStrategy);
    
    /**
     * Allows session creation for storing failure details.
     */
    public void setAllowSessionCreation(boolean allowSessionCreation);
}

ExceptionMappingAuthenticationFailureHandler

Maps exception types to different failure URLs.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import org.springframework.security.core.AuthenticationException;

public class ExceptionMappingAuthenticationFailureHandler 
        extends SimpleUrlAuthenticationFailureHandler {
    
    public ExceptionMappingAuthenticationFailureHandler();
    
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException;
    
    /**
     * Sets exception class name to URL mappings.
     */
    public void setExceptionMappings(Map<?, ?> failureUrlMap);
}

ForwardAuthenticationFailureHandler

Forwards to a target URL on authentication failure.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;

public class ForwardAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     * Creates a handler that forwards to the specified URL.
     */
    public ForwardAuthenticationFailureHandler(String forwardUrl);
    
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException;
}

DelegatingAuthenticationFailureHandler

Delegates to different failure handlers based on exception type.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;

import org.springframework.security.core.AuthenticationException;

public class DelegatingAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     * Creates a delegating handler with exception to handler mappings.
     */
    public DelegatingAuthenticationFailureHandler(
            LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers,
            AuthenticationFailureHandler defaultHandler);
    
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException;
}

AuthenticationEntryPointFailureHandler

Adapts an AuthenticationEntryPoint into an AuthenticationFailureHandler.

package org.springframework.security.web.authentication;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public class AuthenticationEntryPointFailureHandler implements AuthenticationFailureHandler {
    /**
     * Creates a handler that delegates to the entry point.
     */
    public AuthenticationEntryPointFailureHandler(AuthenticationEntryPoint authenticationEntryPoint);
    
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException;
    
    /**
     * Sets whether to rethrow AuthenticationServiceException (default: true).
     */
    public void setRethrowAuthenticationServiceException(boolean rethrowAuthenticationServiceException);
}

HTTP Basic Authentication

BasicAuthenticationFilter

HTTP Basic authentication support.

package org.springframework.security.web.authentication.www;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.filter.OncePerRequestFilter;

public class BasicAuthenticationFilter extends OncePerRequestFilter {
    /**
     * Creates a Basic authentication filter.
     */
    public BasicAuthenticationFilter(AuthenticationManager authenticationManager);
    
    /**
     * Creates a Basic authentication filter with custom entry point.
     */
    public BasicAuthenticationFilter(AuthenticationManager authenticationManager,
                                      AuthenticationEntryPoint authenticationEntryPoint);
    
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException;
    
    public void setAuthenticationConverter(AuthenticationConverter authenticationConverter);
    
    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler);
    
    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler);
    
    public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);
    
    public void setSecurityContextRepository(SecurityContextRepository securityContextRepository);
}

BasicAuthenticationConverter

Converts Basic authentication headers to Authentication objects.

package org.springframework.security.web.authentication.www;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationConverter;

public class BasicAuthenticationConverter implements AuthenticationConverter {
    public BasicAuthenticationConverter();
    
    public Authentication convert(HttpServletRequest request);
    
    public void setAuthenticationDetailsSource(
            AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource);
    
    public void setCredentialsCharset(String credentialsCharset);
}

BasicAuthenticationEntryPoint

Entry point for HTTP Basic authentication.

package org.springframework.security.web.authentication.www;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public class BasicAuthenticationEntryPoint implements AuthenticationEntryPoint {
    public BasicAuthenticationEntryPoint();
    
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException;
    
    /**
     * Sets the realm name for the WWW-Authenticate header.
     */
    public void setRealmName(String realmName);
    
    public String getRealmName();
    
    public void afterPropertiesSet();
}

Digest Authentication

DigestAuthenticationFilter

HTTP Digest authentication support.

package org.springframework.security.web.authentication.www;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.GenericFilterBean;

public class DigestAuthenticationFilter extends GenericFilterBean {
    public DigestAuthenticationFilter();
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;
    
    public void setAuthenticationEntryPoint(DigestAuthenticationEntryPoint authenticationEntryPoint);
    
    public void setUserDetailsService(UserDetailsService userDetailsService);
    
    public void setPasswordAlreadyEncoded(boolean passwordAlreadyEncoded);
    
    public void setCreateAuthenticatedToken(boolean createAuthenticatedToken);
    
    public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);
    
    public void afterPropertiesSet();
}

DigestAuthenticationEntryPoint

Entry point for HTTP Digest authentication.

package org.springframework.security.web.authentication.www;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public class DigestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    public DigestAuthenticationEntryPoint();

    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException;

    /**
     * Sets the realm name.
     */
    public void setRealmName(String realmName);

    /**
     * Sets the key used to generate nonces.
     */
    public void setKey(String key);

    /**
     * Sets the nonce validity period in seconds.
     */
    public void setNonceValiditySeconds(int nonceValiditySeconds);

    public String getRealmName();

    public String getKey();

    public int getNonceValiditySeconds();

    public void afterPropertiesSet();
}

NonceExpiredException

Exception thrown when a digest authentication nonce has expired.

package org.springframework.security.web.authentication.www;

import org.springframework.security.core.AuthenticationException;

public class NonceExpiredException extends AuthenticationException {
    /**
     * Creates an exception for an expired nonce.
     */
    public NonceExpiredException(String message);

    /**
     * Creates an exception for an expired nonce.
     */
    public NonceExpiredException(String message, Throwable cause);
}

Remember-Me Services

RememberMeServices

Interface for remember-me authentication services.

package org.springframework.security.web.authentication;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;

public interface RememberMeServices {
    /**
     * Checks for a remember-me cookie and auto-logins if present.
     */
    Authentication autoLogin(HttpServletRequest request, HttpServletResponse response);
    
    /**
     * Called when authentication fails to allow cleanup.
     */
    void loginFail(HttpServletRequest request, HttpServletResponse response);
    
    /**
     * Called when authentication succeeds to create remember-me cookie.
     */
    void loginSuccess(HttpServletRequest request, HttpServletResponse response,
                      Authentication successfulAuthentication);
}

AbstractRememberMeServices

Base class for remember-me service implementations.

package org.springframework.security.web.authentication.rememberme;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.RememberMeServices;

public abstract class AbstractRememberMeServices implements RememberMeServices {
    public static final String SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY = "remember-me";
    public static final String DEFAULT_PARAMETER = "remember-me";
    public static final int TWO_WEEKS_S = 1209600;

    /**
     * Creates an abstract remember-me service.
     *
     * @param key the key used for token generation
     * @param userDetailsService the user details service
     */
    protected AbstractRememberMeServices(String key, UserDetailsService userDetailsService);

    public final Authentication autoLogin(HttpServletRequest request, HttpServletResponse response);

    public void loginFail(HttpServletRequest request, HttpServletResponse response);

    public void loginSuccess(HttpServletRequest request, HttpServletResponse response,
                             Authentication successfulAuthentication);

    /**
     * Called to process the remember-me cookie.
     */
    protected abstract UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
                                                           HttpServletResponse response);

    /**
     * Called when authentication succeeded to create the cookie.
     */
    protected abstract void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
                                            Authentication successfulAuthentication);

    /**
     * Sets the cookie name (default: "remember-me").
     */
    public void setCookieName(String cookieName);

    /**
     * Sets the remember-me parameter name (default: "remember-me").
     */
    public void setParameter(String parameter);

    /**
     * Sets whether to use secure cookies (default: false).
     */
    public void setUseSecureCookie(boolean useSecureCookie);

    /**
     * Sets the token validity period in seconds (default: 1209600 = 2 weeks).
     */
    public void setTokenValiditySeconds(int tokenValiditySeconds);

    /**
     * Sets whether cookies should always be created regardless of parameter.
     */
    public void setAlwaysRemember(boolean alwaysRemember);

    /**
     * Sets the cookie domain.
     */
    public void setCookieDomain(String cookieDomain);
}

TokenBasedRememberMeServices

Token-based remember-me implementation using hashed cookies.

package org.springframework.security.web.authentication.rememberme;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.RememberMeServices;

public class TokenBasedRememberMeServices extends AbstractRememberMeServices {
    /**
     * Creates token-based remember-me services.
     *
     * @param key the key used for generating tokens
     * @param userDetailsService the user details service
     */
    public TokenBasedRememberMeServices(String key, UserDetailsService userDetailsService);
    
    public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
                               Authentication successfulAuthentication);
    
    /**
     * Sets the algorithm for token matching.
     */
    public void setMatchingAlgorithm(RememberMeTokenAlgorithm matchingAlgorithm);
    
    public String getDigestAlgorithm();
}

PersistentTokenBasedRememberMeServices

Persistent token-based remember-me using database storage.

package org.springframework.security.web.authentication.rememberme;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;

public class PersistentTokenBasedRememberMeServices extends AbstractRememberMeServices {
    public static final int DEFAULT_SERIES_LENGTH = 16;
    public static final int DEFAULT_TOKEN_LENGTH = 16;
    
    /**
     * Creates persistent token-based remember-me services.
     */
    public PersistentTokenBasedRememberMeServices(String key, UserDetailsService userDetailsService,
                                                   PersistentTokenRepository tokenRepository);
    
    public void logout(HttpServletRequest request, HttpServletResponse response,
                       Authentication authentication);
    
    /**
     * Sets the length of the series identifier.
     */
    public void setSeriesLength(int seriesLength);
    
    /**
     * Sets the length of the token value.
     */
    public void setTokenLength(int tokenLength);
    
    /**
     * Sets token validity period in seconds.
     */
    public void setTokenValiditySeconds(int tokenValiditySeconds);
}

PersistentTokenRepository

Repository for persistent remember-me tokens.

package org.springframework.security.web.authentication.rememberme;

import java.util.Date;

public interface PersistentTokenRepository {
    /**
     * Creates a new token.
     */
    void createNewToken(PersistentRememberMeToken token);
    
    /**
     * Updates an existing token.
     */
    void updateToken(String series, String tokenValue, Date lastUsed);
    
    /**
     * Loads a token by series identifier.
     */
    PersistentRememberMeToken getTokenForSeries(String seriesId);
    
    /**
     * Removes all tokens for a user.
     */
    void removeUserTokens(String username);
}

PersistentRememberMeToken

Value object for persistent remember-me tokens.

package org.springframework.security.web.authentication.rememberme;

import java.util.Date;

public class PersistentRememberMeToken {
    /**
     * Creates a persistent remember-me token.
     *
     * @param username the username
     * @param series the series identifier
     * @param tokenValue the token value
     * @param date the last used date
     */
    public PersistentRememberMeToken(String username, String series, String tokenValue, Date date);

    public String getUsername();

    public String getSeries();

    public String getTokenValue();

    public Date getDate();
}

JdbcTokenRepositoryImpl

JDBC-based implementation of PersistentTokenRepository.

package org.springframework.security.web.authentication.rememberme;

import java.util.Date;
import javax.sql.DataSource;

public class JdbcTokenRepositoryImpl implements PersistentTokenRepository {
    public static final String CREATE_TABLE_SQL =
        "create table persistent_logins (username varchar(64) not null, " +
        "series varchar(64) primary key, token varchar(64) not null, " +
        "last_used timestamp not null)";

    public static final String DEF_TOKEN_BY_SERIES_SQL =
        "select username,series,token,last_used from persistent_logins where series = ?";

    public static final String DEF_INSERT_TOKEN_SQL =
        "insert into persistent_logins (username, series, token, last_used) values(?,?,?,?)";

    public static final String DEF_UPDATE_TOKEN_SQL =
        "update persistent_logins set token = ?, last_used = ? where series = ?";

    public static final String DEF_REMOVE_USER_TOKENS_SQL =
        "delete from persistent_logins where username = ?";

    public JdbcTokenRepositoryImpl();

    public void createNewToken(PersistentRememberMeToken token);

    public void updateToken(String series, String tokenValue, Date lastUsed);

    public PersistentRememberMeToken getTokenForSeries(String seriesId);

    public void removeUserTokens(String username);

    public void setDataSource(DataSource dataSource);

    /**
     * Creates the database table on startup.
     */
    public void setCreateTableOnStartup(boolean createTableOnStartup);
}

InMemoryTokenRepositoryImpl

In-memory implementation of PersistentTokenRepository.

package org.springframework.security.web.authentication.rememberme;

import java.util.Date;
import java.util.Map;

public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository {
    public InMemoryTokenRepositoryImpl();

    public void createNewToken(PersistentRememberMeToken token);

    public void updateToken(String series, String tokenValue, Date lastUsed);

    public PersistentRememberMeToken getTokenForSeries(String seriesId);

    public void removeUserTokens(String username);
}

CookieTheftException

Exception thrown when a remember-me cookie theft is detected.

package org.springframework.security.web.authentication.rememberme;

import org.springframework.security.core.AuthenticationException;

public class CookieTheftException extends RememberMeAuthenticationException {
    /**
     * Creates an exception indicating cookie theft.
     */
    public CookieTheftException(String message);

    /**
     * Creates an exception indicating cookie theft.
     */
    public CookieTheftException(String message, Throwable cause);
}

InvalidCookieException

Exception thrown when a remember-me cookie is invalid.

package org.springframework.security.web.authentication.rememberme;

import org.springframework.security.core.AuthenticationException;

public class InvalidCookieException extends RememberMeAuthenticationException {
    /**
     * Creates an exception for an invalid cookie.
     */
    public InvalidCookieException(String message);

    /**
     * Creates an exception for an invalid cookie.
     */
    public InvalidCookieException(String message, Throwable cause);
}

RememberMeAuthenticationException

Base exception for remember-me authentication failures.

package org.springframework.security.web.authentication.rememberme;

import org.springframework.security.core.AuthenticationException;

public class RememberMeAuthenticationException extends AuthenticationException {
    /**
     * Creates a remember-me authentication exception.
     */
    public RememberMeAuthenticationException(String message);

    /**
     * Creates a remember-me authentication exception.
     */
    public RememberMeAuthenticationException(String message, Throwable cause);
}

NullRememberMeServices

A no-op implementation of RememberMeServices that does nothing.

package org.springframework.security.web.authentication;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;

public final class NullRememberMeServices implements RememberMeServices {
    public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response);

    public void loginFail(HttpServletRequest request, HttpServletResponse response);

    public void loginSuccess(HttpServletRequest request, HttpServletResponse response,
                             Authentication successfulAuthentication);
}

RememberMeAuthenticationFilter

Filter that processes remember-me authentication.

package org.springframework.security.web.authentication.rememberme;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.web.filter.GenericFilterBean;

public class RememberMeAuthenticationFilter extends GenericFilterBean {
    /**
     * Creates a remember-me authentication filter.
     */
    public RememberMeAuthenticationFilter(AuthenticationManager authenticationManager,
                                           RememberMeServices rememberMeServices);
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;
    
    public RememberMeServices getRememberMeServices();
    
    public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher);
    
    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler);
    
    public void setSecurityContextRepository(SecurityContextRepository securityContextRepository);
    
    public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);
    
    public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy);
    
    public void afterPropertiesSet();
}

UI and Default Pages

DefaultLoginPageGeneratingFilter

Generates a default login page when no custom login page is configured.

package org.springframework.security.web.authentication.ui;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

import org.springframework.web.filter.GenericFilterBean;

public class DefaultLoginPageGeneratingFilter extends GenericFilterBean {
    public static final String DEFAULT_LOGIN_PAGE_URL = "/login";
    public static final String ERROR_PARAMETER_NAME = "error";

    public DefaultLoginPageGeneratingFilter();

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;

    /**
     * Sets the URL for login processing.
     */
    public void setLoginPageUrl(String loginPageUrl);

    /**
     * Sets whether to enable username/password authentication.
     */
    public void setUsernameParameter(String usernameParameter);

    /**
     * Sets the password parameter name.
     */
    public void setPasswordParameter(String passwordParameter);

    /**
     * Sets whether to enable remember-me.
     */
    public void setRememberMeParameter(String rememberMeParameter);

    /**
     * Sets whether OAuth2 login is enabled.
     */
    public void setOauth2LoginEnabled(boolean oauth2LoginEnabled);

    /**
     * Sets whether SAML2 login is enabled.
     */
    public void setSaml2LoginEnabled(boolean saml2LoginEnabled);
}

DefaultLogoutPageGeneratingFilter

Generates a default logout confirmation page.

package org.springframework.security.web.authentication.ui;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

import org.springframework.web.filter.GenericFilterBean;

public class DefaultLogoutPageGeneratingFilter extends GenericFilterBean {
    public static final String DEFAULT_LOGOUT_PAGE_URL = "/logout";

    public DefaultLogoutPageGeneratingFilter();

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;
}

DefaultResourcesFilter

Serves default static resources for the login page.

package org.springframework.security.web.authentication.ui;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

import org.springframework.web.filter.GenericFilterBean;

public class DefaultResourcesFilter extends GenericFilterBean {
    /**
     * Creates a filter for serving default resources.
     *
     * @since 5.0
     */
    public DefaultResourcesFilter();

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;
}

Anonymous Authentication

AnonymousAuthenticationFilter

Creates anonymous authentication when no authentication is present.

package org.springframework.security.web.authentication;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.web.filter.GenericFilterBean;

public class AnonymousAuthenticationFilter extends GenericFilterBean {
    /**
     * Creates an anonymous authentication filter with default principal "anonymousUser".
     *
     * @param key the key for anonymous tokens
     */
    public AnonymousAuthenticationFilter(String key);
    
    /**
     * Creates an anonymous authentication filter.
     *
     * @param key the key for anonymous tokens
     * @param principal the anonymous principal
     * @param authorities the authorities granted to anonymous users
     */
    public AnonymousAuthenticationFilter(String key, Object principal,
                                          List<GrantedAuthority> authorities);
    
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException;
    
    public void setAuthenticationDetailsSource(
            AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource);
    
    public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);
    
    public Object getPrincipal();
    
    public List<GrantedAuthority> getAuthorities();
    
    public void afterPropertiesSet();
}

One-Time Token Authentication

OneTimeTokenAuthenticationConverter

Converts one-time token from request to Authentication.

package org.springframework.security.web.authentication.ott;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationConverter;

public class OneTimeTokenAuthenticationConverter implements AuthenticationConverter {
    public OneTimeTokenAuthenticationConverter();
    
    public Authentication convert(HttpServletRequest request);
}

GenerateOneTimeTokenRequestResolver

Resolves one-time token generation requests.

package org.springframework.security.web.authentication.ott;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.ott.GenerateOneTimeTokenRequest;

public interface GenerateOneTimeTokenRequestResolver {
    /**
     * Resolves a one-time token generation request from the HTTP request.
     *
     * @param request the HttpServletRequest
     * @return GenerateOneTimeTokenRequest or null
     */
    GenerateOneTimeTokenRequest resolve(HttpServletRequest request);
}

OneTimeTokenGenerationSuccessHandler

Handles successful one-time token generation.

package org.springframework.security.web.authentication.ott;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.ott.OneTimeToken;

public interface OneTimeTokenGenerationSuccessHandler {
    /**
     * Handles generated one-time tokens (e.g., send via email).
     *
     * @param request the request
     * @param response the response
     * @param oneTimeToken the generated token
     */
    void handle(HttpServletRequest request, HttpServletResponse response,
                OneTimeToken oneTimeToken) throws ServletException, IOException;
}

GenerateOneTimeTokenFilter

Filter that generates one-time tokens for authentication (Since 6.4).

package org.springframework.security.web.authentication.ott;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.ott.OneTimeTokenService;
import org.springframework.web.filter.OncePerRequestFilter;

public class GenerateOneTimeTokenFilter extends OncePerRequestFilter {
    /**
     * Creates a filter for generating one-time tokens.
     *
     * @param oneTimeTokenService the one-time token service
     * @since 6.4
     */
    public GenerateOneTimeTokenFilter(OneTimeTokenService oneTimeTokenService);

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException;

    /**
     * Sets the request resolver for one-time token generation.
     */
    public void setGenerateOneTimeTokenRequestResolver(
            GenerateOneTimeTokenRequestResolver generateOneTimeTokenRequestResolver);

    /**
     * Sets the success handler for one-time token generation.
     */
    public void setOneTimeTokenGenerationSuccessHandler(
            OneTimeTokenGenerationSuccessHandler oneTimeTokenGenerationSuccessHandler);
}

OneTimeTokenAuthenticationFilter

Filter that processes one-time token authentication (Since 6.4).

package org.springframework.security.web.authentication.ott;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

public class OneTimeTokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    /**
     * Creates a one-time token authentication filter.
     *
     * @param defaultFilterProcessesUrl the URL to process
     * @param authenticationManager the authentication manager
     * @since 6.4
     */
    public OneTimeTokenAuthenticationFilter(String defaultFilterProcessesUrl,
                                             AuthenticationManager authenticationManager);

    /**
     * Creates a one-time token authentication filter with a request matcher.
     *
     * @param requiresAuthenticationRequestMatcher the request matcher
     * @param authenticationManager the authentication manager
     * @since 6.4
     */
    public OneTimeTokenAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher,
                                             AuthenticationManager authenticationManager);
}

DefaultGenerateOneTimeTokenRequestResolver

Default implementation that resolves one-time token generation requests (Since 6.4).

package org.springframework.security.web.authentication.ott;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.ott.GenerateOneTimeTokenRequest;

public class DefaultGenerateOneTimeTokenRequestResolver implements GenerateOneTimeTokenRequestResolver {
    /**
     * Creates a default request resolver.
     *
     * @since 6.4
     */
    public DefaultGenerateOneTimeTokenRequestResolver();

    public GenerateOneTimeTokenRequest resolve(HttpServletRequest request);

    /**
     * Sets the parameter name for username (default: "username").
     *
     * @param usernameParameter the username parameter name
     */
    public void setUsernameParameter(String usernameParameter);
}

RedirectOneTimeTokenGenerationSuccessHandler

Redirects after successful one-time token generation (Since 6.4).

package org.springframework.security.web.authentication.ott;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.ott.OneTimeToken;

public class RedirectOneTimeTokenGenerationSuccessHandler implements OneTimeTokenGenerationSuccessHandler {
    /**
     * Creates a handler that redirects to the specified URL.
     *
     * @param redirectUrl the URL to redirect to
     * @since 6.4
     */
    public RedirectOneTimeTokenGenerationSuccessHandler(String redirectUrl);

    public void handle(HttpServletRequest request, HttpServletResponse response,
                      OneTimeToken oneTimeToken) throws ServletException, IOException;

    /**
     * Sets the redirect URL.
     *
     * @param redirectUrl the redirect URL
     */
    public void setRedirectUrl(String redirectUrl);
}

DefaultOneTimeTokenSubmitPageGeneratingFilter

Generates a default one-time token submission page (Since 6.4).

package org.springframework.security.web.authentication.ott;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

import org.springframework.web.filter.GenericFilterBean;

public class DefaultOneTimeTokenSubmitPageGeneratingFilter extends GenericFilterBean {
    /**
     * Creates a filter that generates a default one-time token submission page.
     *
     * @since 6.4
     */
    public DefaultOneTimeTokenSubmitPageGeneratingFilter();

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;

    /**
     * Sets the URL for token submission.
     *
     * @param loginProcessingUrl the login processing URL
     */
    public void setLoginProcessingUrl(String loginProcessingUrl);
}

Pre-Authentication

RequestHeaderAuthenticationFilter

Pre-authentication filter using request headers (e.g., CA Siteminder).

package org.springframework.security.web.authentication.preauth;

public class RequestHeaderAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {
    public RequestHeaderAuthenticationFilter();
    
    /**
     * Sets the header name containing the principal.
     */
    public void setPrincipalRequestHeader(String principalRequestHeader);
    
    /**
     * Sets the header name containing credentials.
     */
    public void setCredentialsRequestHeader(String credentialsRequestHeader);
    
    /**
     * Throws exception if header is missing (default: true).
     */
    public void setExceptionIfHeaderMissing(boolean exceptionIfHeaderMissing);
    
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request);
    
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request);
}

RequestAttributeAuthenticationFilter

Pre-authentication filter using request attributes (e.g., Shibboleth).

package org.springframework.security.web.authentication.preauth;

public class RequestAttributeAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {
    public RequestAttributeAuthenticationFilter();
    
    /**
     * Sets the request attribute name containing the principal.
     */
    public void setPrincipalEnvironmentVariable(String principalEnvironmentVariable);
    
    /**
     * Sets the request attribute name containing credentials.
     */
    public void setCredentialsEnvironmentVariable(String credentialsEnvironmentVariable);
    
    /**
     * Throws exception if attribute is missing (default: true).
     */
    public void setExceptionIfVariableMissing(boolean exceptionIfVariableMissing);
    
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request);
    
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request);
}

J2eePreAuthenticatedProcessingFilter

Pre-authentication using J2EE container authentication.

package org.springframework.security.web.authentication.preauth.j2ee;

import jakarta.servlet.http.HttpServletRequest;

public class J2eePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
    public J2eePreAuthenticatedProcessingFilter();
    
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request);
    
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request);
}

X509AuthenticationFilter

Pre-authentication using X.509 client certificates.

package org.springframework.security.web.authentication.preauth.x509;

public class X509AuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {
    public X509AuthenticationFilter();
    
    /**
     * Sets the principal extractor for X.509 certificates.
     */
    public void setPrincipalExtractor(X509PrincipalExtractor principalExtractor);
    
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request);
    
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request);
}

X509PrincipalExtractor

Extracts principal from X.509 certificates.

package org.springframework.security.web.authentication.preauth.x509;

import java.security.cert.X509Certificate;

public interface X509PrincipalExtractor {
    /**
     * Returns the principal for the given certificate.
     *
     * @param clientCert the X.509 certificate
     * @return the principal (usually a String)
     */
    Object extractPrincipal(X509Certificate clientCert);
}

SubjectDnX509PrincipalExtractor

Extracts principal from X.509 Subject DN using regex.

package org.springframework.security.web.authentication.preauth.x509;

import java.security.cert.X509Certificate;

public class SubjectDnX509PrincipalExtractor implements X509PrincipalExtractor {
    public SubjectDnX509PrincipalExtractor();
    
    public Object extractPrincipal(X509Certificate clientCert);
    
    /**
     * Sets the regex for extracting the principal from Subject DN.
     * Default: "CN=(.*?)(?:,|$)"
     */
    public void setSubjectDnRegex(String subjectDnRegex);
    
    public void setMessageSource(MessageSource messageSource);
}

Switch User

SwitchUserFilter

Allows administrators to switch to another user's context.

package org.springframework.security.web.authentication.switchuser;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.GenericFilterBean;

public class SwitchUserFilter extends GenericFilterBean {
    public static final String SPRING_SECURITY_SWITCH_USERNAME_KEY = "username";
    public static final String ROLE_PREVIOUS_ADMINISTRATOR = "ROLE_PREVIOUS_ADMINISTRATOR";
    
    public SwitchUserFilter();
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException;
    
    /**
     * Sets the UserDetailsService for loading target users.
     */
    public void setUserDetailsService(UserDetailsService userDetailsService);
    
    /**
     * Sets the URL for exiting switch user mode.
     */
    public void setExitUserUrl(String exitUserUrl);
    
    /**
     * Sets the request matcher for exiting switch user mode.
     */
    public void setExitUserMatcher(RequestMatcher exitUserMatcher);
    
    /**
     * Sets the URL for switching users.
     */
    public void setSwitchUserUrl(String switchUserUrl);
    
    /**
     * Sets the request matcher for switching users.
     */
    public void setSwitchUserMatcher(RequestMatcher switchUserMatcher);
    
    /**
     * Sets the username parameter name (default: "username").
     */
    public void setUsernameParameter(String usernameParameter);
    
    public void setAuthenticationDetailsSource(
            AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource);
    
    public void setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger);
    
    public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher);
    
    public void setMessageSource(MessageSource messageSource);

    public void afterPropertiesSet();
}

SwitchUserGrantedAuthority

Special GrantedAuthority that stores the original authentication for switch user functionality.

package org.springframework.security.web.authentication.switchuser;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

public class SwitchUserGrantedAuthority implements GrantedAuthority {
    /**
     * Creates a switch user granted authority.
     *
     * @param role the authority name
     * @param source the original authentication
     */
    public SwitchUserGrantedAuthority(String role, Authentication source);

    public String getAuthority();

    /**
     * Returns the original authentication before switching.
     */
    public Authentication getSource();
}

AuthenticationSwitchUserEvent

Event published when a user switches to another user's context.

package org.springframework.security.authentication.event;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

public class AuthenticationSwitchUserEvent extends AbstractAuthenticationEvent {
    /**
     * Creates an authentication switch user event.
     *
     * @param authentication the target user authentication
     * @param targetUser the target user details
     */
    public AuthenticationSwitchUserEvent(Authentication authentication, UserDetails targetUser);

    /**
     * Returns the target user details.
     */
    public UserDetails getTargetUser();
}

SwitchUserAuthorityChanger

Interface for customizing authorities when switching users.

package org.springframework.security.web.authentication.switchuser;

import java.util.Collection;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

public interface SwitchUserAuthorityChanger {
    /**
     * Modifies authorities for the switched user context.
     *
     * @param targetUser the target user authentication
     * @param currentAuthentication the current authentication
     * @param authorities the original authorities
     * @return modified collection of authorities
     */
    Collection<GrantedAuthority> modifyGrantedAuthorities(Authentication targetUser,
                                                           Authentication currentAuthentication,
                                                           Collection<? extends GrantedAuthority> authorities);
}

Authentication Details

WebAuthenticationDetails

Holds HTTP request details for authentication.

package org.springframework.security.web.authentication;

import jakarta.servlet.http.HttpServletRequest;

public class WebAuthenticationDetails {
    /**
     * Creates authentication details from the request.
     */
    public WebAuthenticationDetails(HttpServletRequest request);
    
    /**
     * Returns the remote IP address.
     */
    public String getRemoteAddress();
    
    /**
     * Returns the session ID.
     */
    public String getSessionId();
    
    public boolean equals(Object o);
    
    public int hashCode();
    
    public String toString();
}

WebAuthenticationDetailsSource

Creates WebAuthenticationDetails from requests.

package org.springframework.security.web.authentication;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AuthenticationDetailsSource;

public class WebAuthenticationDetailsSource 
        implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {
    
    public WebAuthenticationDetailsSource();
    
    /**
     * Builds WebAuthenticationDetails from the request.
     */
    public WebAuthenticationDetails buildDetails(HttpServletRequest context);
}

Usage Examples

Form Login Configuration

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class FormLoginConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .formLogin(form -> form
                .loginPage("/login")
                .loginProcessingUrl("/perform_login")
                .usernameParameter("email")
                .passwordParameter("pass")
                .defaultSuccessUrl("/dashboard", true)
                .failureUrl("/login?error=true")
                .permitAll()
            );
        
        return http.build();
    }
}

Remember-Me Configuration

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class RememberMeConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, DataSource dataSource) throws Exception {
        http
            .rememberMe(remember -> remember
                .key("uniqueAndSecret")
                .tokenRepository(persistentTokenRepository(dataSource))
                .tokenValiditySeconds(86400) // 1 day
                .rememberMeParameter("remember-me")
                .rememberMeCookieName("my-remember-me")
                .userDetailsService(userDetailsService())
            );
        
        return http.build();
    }
    
    @Bean
    public PersistentTokenRepository persistentTokenRepository(DataSource dataSource) {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        return tokenRepository;
    }
}

Custom Authentication Filter with Multiple Converters

import org.springframework.security.web.authentication.AuthenticationFilter;
import org.springframework.security.web.authentication.DelegatingAuthenticationConverter;
import org.springframework.security.web.authentication.www.BasicAuthenticationConverter;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;

@Configuration
public class MultiAuthConverterConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, 
                                           AuthenticationManager authenticationManager) throws Exception {
        
        // Create a delegating converter that tries multiple authentication methods
        DelegatingAuthenticationConverter converter = new DelegatingAuthenticationConverter(
            Arrays.asList(
                new BasicAuthenticationConverter(),  // Try HTTP Basic first
                new BearerTokenAuthenticationConverter(),  // Then Bearer token
                new CustomHeaderAuthenticationConverter()   // Finally custom header
            )
        );
        
        AuthenticationFilter authFilter = new AuthenticationFilter(
            authenticationManager,
            converter
        );
        authFilter.setRequestMatcher(
            PathPatternRequestMatcher.pathPattern("/api/**")
        );
        authFilter.setSuccessHandler(new HttpStatusReturningAuthenticationSuccessHandler());
        authFilter.setFailureHandler(new HttpStatusAuthenticationFailureHandler());
        
        http
            .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/api/**").authenticated()
                .anyRequest().permitAll()
            );
        
        return http.build();
    }
}

Handling Authentication Exceptions with Custom Logic

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

public class DetailedAuthenticationFailureHandler implements AuthenticationFailureHandler {
    
    private final AuditService auditService;
    private final AccountLockoutService lockoutService;
    
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, 
                                        HttpServletResponse response,
                                        AuthenticationException exception) 
            throws IOException, ServletException {
        
        String username = request.getParameter("username");
        String ipAddress = request.getRemoteAddr();
        
        // Log authentication failure
        auditService.logAuthenticationFailure(username, ipAddress, exception.getClass().getSimpleName());
        
        // Handle account lockout
        if (exception instanceof BadCredentialsException) {
            lockoutService.recordFailedAttempt(username, ipAddress);
            
            if (lockoutService.isLocked(username)) {
                response.sendRedirect("/login?error=locked");
                return;
            }
        }
        
        // Different error messages for different exception types
        String errorMessage;
        if (exception instanceof AccountExpiredException) {
            errorMessage = "account_expired";
        } else if (exception instanceof LockedException) {
            errorMessage = "account_locked";
        } else if (exception instanceof BadCredentialsException) {
            errorMessage = "bad_credentials";
        } else {
            errorMessage = "authentication_failed";
        }
        
        // For AJAX requests, return JSON
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            response.getWriter().write(
                String.format("{\"error\": \"%s\", \"message\": \"%s\"}", 
                    errorMessage, exception.getMessage())
            );
        } else {
            // For regular requests, redirect with error parameter
            response.sendRedirect("/login?error=" + errorMessage);
        }
    }
}

One-Time Token Authentication Flow

import org.springframework.security.web.authentication.ott.GenerateOneTimeTokenFilter;
import org.springframework.security.web.authentication.ott.OneTimeTokenAuthenticationFilter;
import org.springframework.security.authentication.ott.OneTimeTokenService;

@Configuration
public class OneTimeTokenConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http,
                                           AuthenticationManager authenticationManager,
                                           OneTimeTokenService oneTimeTokenService) throws Exception {
        
        // Filter to generate OTT
        GenerateOneTimeTokenFilter generateFilter = new GenerateOneTimeTokenFilter(oneTimeTokenService);
        generateFilter.setGenerateOneTimeTokenRequestResolver(
            new DefaultGenerateOneTimeTokenRequestResolver()
        );
        generateFilter.setOneTimeTokenGenerationSuccessHandler(
            new RedirectOneTimeTokenGenerationSuccessHandler("/ott-sent")
        );
        
        // Filter to authenticate with OTT
        OneTimeTokenAuthenticationFilter authFilter = 
            new OneTimeTokenAuthenticationFilter("/login/ott", authenticationManager);
        
        http
            .addFilterBefore(generateFilter, UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/login/ott/generate").permitAll()
                .requestMatchers("/login/ott").permitAll()
                .anyRequest().authenticated()
            );
        
        return http.build();
    }
}

Custom Authentication Success Handler

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

public class CustomSuccessHandler implements AuthenticationSuccessHandler {
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, 
                                        HttpServletResponse response,
                                        Authentication authentication) 
            throws IOException, ServletException {
        
        Set<String> roles = authentication.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.toSet());
        
        if (roles.contains("ROLE_ADMIN")) {
            response.sendRedirect("/admin/dashboard");
        } else if (roles.contains("ROLE_USER")) {
            response.sendRedirect("/user/dashboard");
        } else {
            response.sendRedirect("/");
        }
    }
}

Switch User Configuration

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SwitchUserConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .switchUser(switchUser -> switchUser
                .switchUserUrl("/admin/switch-user")
                .exitUserUrl("/admin/exit-switch")
                .switchUserParameter("username")
                .targetUrl("/user/dashboard")
            );
        
        return http.build();
    }
}

Handling Authentication Exceptions

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;

@Configuration
public class ExceptionHandlingConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .formLogin(form -> form
                .loginPage("/login")
                .failureHandler(authenticationFailureHandler())
            );
        
        return http.build();
    }
    
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        Map<String, String> failureUrlMap = new HashMap<>();
        failureUrlMap.put(BadCredentialsException.class.getName(), "/login?error=bad-credentials");
        failureUrlMap.put(AccountExpiredException.class.getName(), "/login?error=account-expired");
        failureUrlMap.put(LockedException.class.getName(), "/login?error=account-locked");
        
        ExceptionMappingAuthenticationFailureHandler handler = 
            new ExceptionMappingAuthenticationFailureHandler();
        handler.setExceptionMappings(failureUrlMap);
        handler.setDefaultFailureUrl("/login?error=authentication-failed");
        
        return handler;
    }
}

Custom Authentication Converter with Error Handling

import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.core.Authentication;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

public class CustomAuthenticationConverter implements AuthenticationConverter {
    
    @Override
    public Authentication convert(HttpServletRequest request) {
        String username = request.getParameter("email"); // Custom parameter name
        String password = request.getParameter("pass");
        
        // Return null if no credentials provided (skip authentication)
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            return null;
        }
        
        // Validate format
        if (!isValidEmail(username)) {
            throw new IllegalArgumentException("Invalid email format");
        }
        
        return new UsernamePasswordAuthenticationToken(username, password);
    }
    
    private boolean isValidEmail(String email) {
        return email != null && email.contains("@") && email.contains(".");
    }
}

Remember-Me with Token Rotation

import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

@Configuration
public class RememberMeTokenRotationConfig {
    
    @Bean
    public PersistentTokenRepository persistentTokenRepository(DataSource dataSource) {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        tokenRepository.setCreateTableOnStartup(true); // Only for development
        
        return tokenRepository;
    }
    
    @Bean
    public PersistentTokenBasedRememberMeServices rememberMeServices(
            UserDetailsService userDetailsService,
            PersistentTokenRepository tokenRepository) {
        
        PersistentTokenBasedRememberMeServices services = 
            new PersistentTokenBasedRememberMeServices(
                "uniqueAndSecretKey",
                userDetailsService,
                tokenRepository
            );
        
        // Configure token rotation
        services.setTokenValiditySeconds(86400 * 30); // 30 days
        services.setSeriesLength(16);
        services.setTokenLength(16);
        services.setCookieName("remember-me");
        services.setUseSecureCookie(true);
        
        return services;
    }
}

One-Time Token with Custom Delivery

import org.springframework.security.web.authentication.ott.GenerateOneTimeTokenFilter;
import org.springframework.security.web.authentication.ott.OneTimeTokenGenerationSuccessHandler;
import org.springframework.security.authentication.ott.OneTimeToken;

@Configuration
public class CustomOttConfig {
    
    @Bean
    public GenerateOneTimeTokenFilter generateOneTimeTokenFilter(
            OneTimeTokenService oneTimeTokenService,
            EmailService emailService) {
        
        GenerateOneTimeTokenFilter filter = 
            new GenerateOneTimeTokenFilter(oneTimeTokenService);
        
        filter.setOneTimeTokenGenerationSuccessHandler(
            new OneTimeTokenGenerationSuccessHandler() {
                @Override
                public void handle(HttpServletRequest request, 
                                  HttpServletResponse response,
                                  OneTimeToken oneTimeToken) 
                        throws ServletException, IOException {
                    
                    String username = request.getParameter("username");
                    String token = oneTimeToken.getToken();
                    
                    // Send token via email
                    emailService.sendTokenEmail(username, token);
                    
                    // Redirect to token entry page
                    response.sendRedirect("/login/ott?sent=true");
                }
            }
        );
        
        return filter;
    }
}

Pre-Authentication with Header Validation

import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

@Configuration
public class PreAuthHeaderConfig {
    
    @Bean
    public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter(
            AuthenticationManager authenticationManager) {
        
        RequestHeaderAuthenticationFilter filter = 
            new RequestHeaderAuthenticationFilter();
        
        filter.setPrincipalRequestHeader("X-User-Id");
        filter.setCredentialsRequestHeader("X-User-Roles");
        filter.setExceptionIfHeaderMissing(true);
        filter.setAuthenticationManager(authenticationManager);
        
        // Add validation
        filter.setCheckForPrincipalChanges(true);
        filter.setInvalidateSessionOnPrincipalChange(true);
        
        return filter;
    }
}