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 access control framework provides comprehensive authorization mechanisms, exception handling, and privilege evaluation for web resources. It handles access denied scenarios and integrates with authorization managers to enforce security policies.
Access denied handlers define how to respond when access is denied to authenticated users.
public interface AccessDeniedHandler {
// Handle access denied scenarios
void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException;
}The ExceptionTranslationFilter converts security exceptions into appropriate HTTP responses.
public class ExceptionTranslationFilter extends GenericFilterBean {
// Constructors
public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint);
public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint,
RequestCache requestCache);
// Configuration methods
public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler);
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint);
public void setRequestCache(RequestCache requestCache);
public void setAuthenticationTrustResolver(AuthenticationTrustResolver authenticationTrustResolver);
public void setThrowableAnalyzer(ThrowableAnalyzer throwableAnalyzer);
// Filter implementation
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException;
}Forwards to an error page when access is denied.
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
// Constructor
public AccessDeniedHandlerImpl();
// Configuration
public void setErrorPage(String errorPage);
// AccessDeniedHandler implementation
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException;
}Returns an HTTP status code when access is denied.
public class HttpStatusAccessDeniedHandler implements AccessDeniedHandler {
// Constructor
public HttpStatusAccessDeniedHandler(HttpStatus httpStatus);
// AccessDeniedHandler implementation
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException;
}Delegates to different handlers based on request characteristics or exception types.
public class DelegatingAccessDeniedHandler implements AccessDeniedHandler {
// Constructor
public DelegatingAccessDeniedHandler(Map<Class<? extends AccessDeniedException>, AccessDeniedHandler> handlers,
AccessDeniedHandler defaultHandler);
// AccessDeniedHandler implementation
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException;
}
public class RequestMatcherDelegatingAccessDeniedHandler implements AccessDeniedHandler {
// Constructor
public RequestMatcherDelegatingAccessDeniedHandler(Map<RequestMatcher, AccessDeniedHandler> handlers,
AccessDeniedHandler defaultHandler);
// AccessDeniedHandler implementation
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException;
}// Forward to error page
AccessDeniedHandlerImpl pageHandler = new AccessDeniedHandlerImpl();
pageHandler.setErrorPage("/access-denied");
// Return 403 status
HttpStatusAccessDeniedHandler statusHandler =
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN);
// Different handlers for different request types
Map<RequestMatcher, AccessDeniedHandler> handlerMap = Map.of(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"), statusHandler,
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON), statusHandler
);
RequestMatcherDelegatingAccessDeniedHandler delegatingHandler =
new RequestMatcherDelegatingAccessDeniedHandler(handlerMap, pageHandler);
// Configure exception translation filter
ExceptionTranslationFilter exceptionFilter = new ExceptionTranslationFilter(authenticationEntryPoint);
exceptionFilter.setAccessDeniedHandler(delegatingHandler);Evaluates whether access should be allowed to web resources.
public interface WebInvocationPrivilegeEvaluator {
// Check access to URI
boolean isAllowed(String uri, Authentication authentication);
// Check access to HTTP request
boolean isAllowed(HttpServletRequest request, Authentication authentication);
}public class DefaultWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator {
// Constructor
public DefaultWebInvocationPrivilegeEvaluator(FilterInvocationSecurityMetadataSource securityMetadataSource,
AuthenticationManager authenticationManager,
AccessDecisionManager accessDecisionManager);
// WebInvocationPrivilegeEvaluator implementation
public boolean isAllowed(String uri, Authentication authentication);
public boolean isAllowed(HttpServletRequest request, Authentication authentication);
}public final class AuthorizationManagerWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator {
// Constructor
public AuthorizationManagerWebInvocationPrivilegeEvaluator(AuthorizationManager<RequestAuthorizationContext> authorizationManager);
// WebInvocationPrivilegeEvaluator implementation
public boolean isAllowed(String uri, Authentication authentication);
public boolean isAllowed(HttpServletRequest request, Authentication authentication);
}// Check if user can access specific URLs
WebInvocationPrivilegeEvaluator evaluator = new AuthorizationManagerWebInvocationPrivilegeEvaluator(
authorizationManager
);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// Check access to specific URI
boolean canAccessAdmin = evaluator.isAllowed("/admin/users", auth);
boolean canAccessProfile = evaluator.isAllowed("/profile", auth);
// Check access to current request
boolean canAccessCurrent = evaluator.isAllowed(request, auth);Authorizes requests based on IP address patterns.
public final class IpAddressAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
// Static factory methods
public static IpAddressAuthorizationManager hasIpAddress(String ipAddress);
public static IpAddressAuthorizationManager hasIpAddressRange(String ipAddressRange);
// AuthorizationManager implementation
public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context);
}// Allow access only from specific IP ranges
AuthorizationManager<RequestAuthorizationContext> ipAuth =
IpAddressAuthorizationManager.hasIpAddress("192.168.1.0/24")
.or(IpAddressAuthorizationManager.hasIpAddress("10.0.0.0/8"));
// Configure in security chain
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").access(ipAuth)
.anyRequest().authenticated()
);Transform requests for authorization processing.
public final class HandlerMappingIntrospectorRequestTransformer implements AuthorizationManagerRequestTransformer {
// Constructor
public HandlerMappingIntrospectorRequestTransformer(HandlerMappingIntrospector handlerMappingIntrospector);
// AuthorizationManagerRequestTransformer implementation
public HttpServletRequest transform(HttpServletRequest request);
}
public final class PathPatternRequestTransformer implementsAuthorizationManagerRequestTransformer {
// Static factory method
public static PathPatternRequestTransformer pathPattern();
// AuthorizationManagerRequestTransformer implementation
public HttpServletRequest transform(HttpServletRequest request);
}Executes multiple access denied handlers in sequence.
public class CompositeAccessDeniedHandler implements AccessDeniedHandler {
// Constructor
public CompositeAccessDeniedHandler(AccessDeniedHandler... accessDeniedHandlers);
public CompositeAccessDeniedHandler(List<AccessDeniedHandler> accessDeniedHandlers);
// AccessDeniedHandler implementation
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException;
}// Execute multiple handlers for access denied
CompositeAccessDeniedHandler composite = new CompositeAccessDeniedHandler(
new AuditAccessDeniedHandler(), // Log the access denial
new MetricsAccessDeniedHandler(), // Record metrics
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN) // Return response
);// Basic setup for web applications
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
new LoginUrlAuthenticationEntryPoint("/login")
);
filter.setAccessDeniedHandler(new AccessDeniedHandlerImpl("/access-denied"));// Setup for REST APIs
ExceptionTranslationFilter apiFilter = new ExceptionTranslationFilter(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
);
apiFilter.setAccessDeniedHandler(new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN));// Different handling for web vs API requests
Map<RequestMatcher, AccessDeniedHandler> accessDeniedHandlers = Map.of(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"),
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN),
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON),
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN)
);
RequestMatcherDelegatingAccessDeniedHandler delegating =
new RequestMatcherDelegatingAccessDeniedHandler(
accessDeniedHandlers,
new AccessDeniedHandlerImpl("/access-denied")
);
Map<RequestMatcher, AuthenticationEntryPoint> entryPoints = Map.of(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"),
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON),
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
);
DelegatingAuthenticationEntryPoint delegatingEntry =
new DelegatingAuthenticationEntryPoint(entryPoints);
delegatingEntry.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(delegatingEntry);
filter.setAccessDeniedHandler(delegating);Common exceptions in access control:
The ExceptionTranslationFilter catches these exceptions and converts them to appropriate HTTP responses based on the configured handlers.
Install with Tessl CLI
npx tessl i tessl/maven-org-springframework-security--spring-security-web