Spring Security Web module provides comprehensive web security features for Spring-based applications, including servlet-based authentication, authorization, CSRF protection, session management, and security filter chain implementation
—
Spring Security Web's authentication framework provides comprehensive mechanisms for user authentication, including form-based login, HTTP Basic authentication, and extensible authentication processing. The framework is built around pluggable authentication handlers, converters, and entry points.
Authentication handlers define what happens after authentication attempts succeed or fail.
public interface AuthenticationSuccessHandler {
// Called when authentication succeeds
void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
// Called when authentication succeeds with filter chain continuation
default void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, Authentication authentication)
throws IOException, ServletException;
}
public interface AuthenticationFailureHandler {
// Called when authentication fails
void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException;
}Entry points define how to commence authentication when it's required.
public interface AuthenticationEntryPoint {
// Commences authentication (e.g., redirect to login page, return 401)
void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException;
}The primary filter for handling form-based login.
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
// Default parameter names
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
// Configuration methods
public void setUsernameParameter(String usernameParameter);
public void setPasswordParameter(String passwordParameter);
public void setPostOnly(boolean postOnly);
// Authentication processing
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException;
}// Configure form-based authentication
UsernamePasswordAuthenticationFilter authFilter = new UsernamePasswordAuthenticationFilter();
authFilter.setAuthenticationManager(authenticationManager);
// Custom parameter names
authFilter.setUsernameParameter("email");
authFilter.setPasswordParameter("pwd");
// Custom login URL
authFilter.setRequiresAuthenticationRequestMatcher(
new AntPathRequestMatcher("/custom-login", "POST")
);
// Success handler - redirect to dashboard
authFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/dashboard"));
// Failure handler - return to login with error
authFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error"));Redirects to a configured URL on successful authentication.
public class SimpleUrlAuthenticationSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
implements AuthenticationSuccessHandler {
// Constructors
public SimpleUrlAuthenticationSuccessHandler();
public SimpleUrlAuthenticationSuccessHandler(String defaultTargetUrl);
// Configuration
public void setDefaultTargetUrl(String defaultTargetUrl);
public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl);
public void setTargetUrlParameter(String targetUrlParameter);
// AuthenticationSuccessHandler implementation
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
}Redirects to originally requested URL after authentication.
public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
// Configuration
public void setRequestCache(RequestCache requestCache);
public void setTargetUrlParameter(String targetUrlParameter);
// Handles redirect to saved request or default URL
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
}public class ForwardAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
// Constructor
public ForwardAuthenticationSuccessHandler(String forwardUrl);
// AuthenticationSuccessHandler implementation
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
}
public class HttpMessageConverterAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
// Constructor
public HttpMessageConverterAuthenticationSuccessHandler();
// Configuration
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters);
// AuthenticationSuccessHandler implementation
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
}// Redirect to originally requested page
SavedRequestAwareAuthenticationSuccessHandler successHandler =
new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setDefaultTargetUrl("/dashboard");
successHandler.setTargetUrlParameter("continue");
// Always redirect to specific URL
SimpleUrlAuthenticationSuccessHandler simpleHandler =
new SimpleUrlAuthenticationSuccessHandler("/admin/welcome");
simpleHandler.setAlwaysUseDefaultTargetUrl(true);Redirects to a configured URL on authentication failure.
public class SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {
// Constructors
public SimpleUrlAuthenticationFailureHandler();
public SimpleUrlAuthenticationFailureHandler(String defaultFailureUrl);
// Configuration
public void setDefaultFailureUrl(String defaultFailureUrl);
public void setAllowSessionCreation(boolean allowSessionCreation);
public void setUseForward(boolean forwardToDestination);
// AuthenticationFailureHandler implementation
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException;
}Maps different exception types to different failure URLs.
public class ExceptionMappingAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
// Configure exception to URL mappings
public void setExceptionMappings(Properties exceptionMappings);
// Map specific exception to URL
public void setDefaultFailureUrl(String defaultFailureUrl);
}public class ForwardAuthenticationFailureHandler implements AuthenticationFailureHandler {
// Constructor
public ForwardAuthenticationFailureHandler(String forwardUrl);
// AuthenticationFailureHandler implementation
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException;
}
public class DelegatingAuthenticationFailureHandler implements AuthenticationFailureHandler {
// Constructor
public DelegatingAuthenticationFailureHandler(
LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers,
AuthenticationFailureHandler defaultHandler);
// AuthenticationFailureHandler implementation
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException;
}
public class AuthenticationEntryPointFailureHandler implements AuthenticationFailureHandler {
// Constructor
public AuthenticationEntryPointFailureHandler(AuthenticationEntryPoint authenticationEntryPoint);
// AuthenticationFailureHandler implementation
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException;
}// Map different exceptions to different error pages
ExceptionMappingAuthenticationFailureHandler failureHandler =
new ExceptionMappingAuthenticationFailureHandler();
Properties mappings = new Properties();
mappings.put("org.springframework.security.authentication.BadCredentialsException",
"/login?error=invalid");
mappings.put("org.springframework.security.authentication.DisabledException",
"/login?error=disabled");
mappings.put("org.springframework.security.authentication.LockedException",
"/login?error=locked");
failureHandler.setExceptionMappings(mappings);
failureHandler.setDefaultFailureUrl("/login?error=unknown");Redirects unauthenticated users to a login page.
public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint {
// Constructors
public LoginUrlAuthenticationEntryPoint(String loginFormUrl);
// Configuration
public void setForceHttps(boolean forceHttps);
public void setUseForward(boolean useForward);
public void setPortMapper(PortMapper portMapper);
public void setPortResolver(PortResolver portResolver);
// AuthenticationEntryPoint implementation
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException;
}Returns an HTTP status code instead of redirecting.
public class HttpStatusEntryPoint implements AuthenticationEntryPoint {
// Constructor
public HttpStatusEntryPoint(HttpStatus httpStatus);
// AuthenticationEntryPoint implementation
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException;
}public class Http403ForbiddenEntryPoint implements AuthenticationEntryPoint {
// AuthenticationEntryPoint implementation
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException;
}
public class NoOpAuthenticationEntryPoint implements AuthenticationEntryPoint {
// AuthenticationEntryPoint implementation
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException;
}Delegates to different entry points based on request matching.
public class DelegatingAuthenticationEntryPoint implements AuthenticationEntryPoint {
// Constructor
public DelegatingAuthenticationEntryPoint(LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints);
// Configuration
public void setDefaultEntryPoint(AuthenticationEntryPoint defaultEntryPoint);
// AuthenticationEntryPoint implementation
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException;
}// Redirect to login page
LoginUrlAuthenticationEntryPoint loginEntry = new LoginUrlAuthenticationEntryPoint("/login");
loginEntry.setForceHttps(true);
loginEntry.setUseForward(false);
// Return 401 for API endpoints
HttpStatusEntryPoint apiEntry = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
// Delegating entry point based on request type
DelegatingAuthenticationEntryPoint delegatingEntry = new DelegatingAuthenticationEntryPoint(
Map.of(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"), apiEntry,
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON), apiEntry
)
);
delegatingEntry.setDefaultEntryPoint(loginEntry);Authentication converters extract authentication information from HTTP requests.
public interface AuthenticationConverter {
// Convert request to Authentication object
Authentication convert(HttpServletRequest request);
}
public class DelegatingAuthenticationConverter implements AuthenticationConverter {
// Constructor
public DelegatingAuthenticationConverter(List<AuthenticationConverter> delegates);
// AuthenticationConverter implementation
public Authentication convert(HttpServletRequest request);
}Resolves authentication managers based on request characteristics.
public class RequestMatcherDelegatingAuthenticationManagerResolver
implements AuthenticationManagerResolver<HttpServletRequest> {
// Constructor
public RequestMatcherDelegatingAuthenticationManagerResolver(
LinkedHashMap<RequestMatcher, AuthenticationManager> authenticationManagers);
// Configuration
public void setDefaultAuthenticationManager(AuthenticationManager defaultAuthenticationManager);
// AuthenticationManagerResolver implementation
public AuthenticationManager resolve(HttpServletRequest request);
}Provides anonymous authentication when no other authentication is present.
public class AnonymousAuthenticationFilter extends GenericFilterBean {
// Constructors
public AnonymousAuthenticationFilter(String key);
public AnonymousAuthenticationFilter(String key, Object principal,
Collection<? extends GrantedAuthority> authorities);
// Filter implementation
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException;
}// Configure anonymous authentication
AnonymousAuthenticationFilter anonymousFilter = new AnonymousAuthenticationFilter(
"anonymousKey",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))
);Captures additional web-specific authentication information.
public class WebAuthenticationDetails implements Serializable {
// Constructor
public WebAuthenticationDetails(HttpServletRequest request);
// Access methods
public String getRemoteAddress();
public String getSessionId();
}
public class WebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {
// AuthenticationDetailsSource implementation
public WebAuthenticationDetails buildDetails(HttpServletRequest context);
}Provides persistent login functionality across browser sessions.
public interface RememberMeServices {
// Attempt automatic login
Authentication autoLogin(HttpServletRequest request, HttpServletResponse response);
// Handle login failure
void loginFail(HttpServletRequest request, HttpServletResponse response);
// Handle login success
void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication);
}Spring Security provides comprehensive logout functionality to handle user logout and session cleanup.
The main filter that handles logout requests.
public class LogoutFilter extends GenericFilterBean {
// Constructor
public LogoutFilter(String logoutSuccessUrl, LogoutHandler... handlers);
public LogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers);
// Configuration
public void setFilterProcessesUrl(String filterProcessesUrl);
public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher);
// Filter implementation
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException;
}Handle various logout tasks such as clearing security context and invalidating sessions.
public interface LogoutHandler {
// Perform logout operations
void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
}
public class SecurityContextLogoutHandler implements LogoutHandler {
// Configuration
public void setInvalidateHttpSession(boolean invalidateHttpSession);
public void setClearAuthentication(boolean clearAuthentication);
// LogoutHandler implementation
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
}
public class CookieClearingLogoutHandler implements LogoutHandler {
// Constructor
public CookieClearingLogoutHandler(String... cookiesToClear);
// LogoutHandler implementation
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
}
public class HeaderWriterLogoutHandler implements LogoutHandler {
// Constructor
public HeaderWriterLogoutHandler(HeaderWriter... headerWriters);
// LogoutHandler implementation
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
}Define what happens after successful logout.
public interface LogoutSuccessHandler {
// Handle successful logout
void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
}
public class SimpleUrlLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
implements LogoutSuccessHandler {
// Constructor
public SimpleUrlLogoutSuccessHandler();
// Configuration
public void setDefaultTargetUrl(String defaultTargetUrl);
// LogoutSuccessHandler implementation
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
}
public class HttpStatusReturningLogoutSuccessHandler implements LogoutSuccessHandler {
// Constructor
public HttpStatusReturningLogoutSuccessHandler(HttpStatus httpStatusToReturn);
// LogoutSuccessHandler implementation
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException;
}// Basic logout configuration
List<LogoutHandler> handlers = Arrays.asList(
new SecurityContextLogoutHandler(),
new CookieClearingLogoutHandler("JSESSIONID", "remember-me")
);
LogoutFilter logoutFilter = new LogoutFilter("/login?logout", handlers.toArray(new LogoutHandler[0]));
logoutFilter.setFilterProcessesUrl("/logout");
// Custom logout success handler
SimpleUrlLogoutSuccessHandler successHandler = new SimpleUrlLogoutSuccessHandler();
successHandler.setDefaultTargetUrl("/goodbye");
LogoutFilter customLogout = new LogoutFilter(successHandler, handlers.toArray(new LogoutHandler[0]));// Complete authentication setup for web application
UsernamePasswordAuthenticationFilter authFilter = new UsernamePasswordAuthenticationFilter();
authFilter.setAuthenticationManager(authenticationManager);
authFilter.setAuthenticationSuccessHandler(
new SavedRequestAwareAuthenticationSuccessHandler()
);
authFilter.setAuthenticationFailureHandler(
new SimpleUrlAuthenticationFailureHandler("/login?error")
);
AnonymousAuthenticationFilter anonymousFilter = new AnonymousAuthenticationFilter("key");
List<Filter> filters = Arrays.asList(
new SecurityContextHolderFilter(repository),
authFilter,
anonymousFilter
);// Custom authentication converter for API keys
AuthenticationConverter apiKeyConverter = request -> {
String apiKey = request.getHeader("X-API-Key");
return apiKey != null ? new ApiKeyAuthenticationToken(apiKey) : null;
};
AuthenticationFilter apiFilter = new AuthenticationFilter(
authenticationManager,
apiKeyConverter
);
apiFilter.setSuccessHandler((req, res, chain, auth) -> chain.doFilter(req, res));
apiFilter.setFailureHandler(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));Install with Tessl CLI
npx tessl i tessl/maven-org-springframework-security--spring-security-web