CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springframework-security--spring-security-web

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

Pending
Overview
Eval results
Files

access-control.mddocs/

Access Control and Authorization

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.

Core Access Control Components

Access Denied Handling

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;
}

Exception Translation

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;
}

Access Denied Handlers

Default Access Denied Handler

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;
}

HTTP Status Access Denied Handler

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;
}

Delegating Access Denied Handler

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;
}

Usage Examples

// 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);

Web Invocation Privilege Evaluator

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);
}

Default Implementation

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);
}

Authorization Manager Based Implementation

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);
}

Usage Example

// 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);

IP Address Authorization

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);
}

Usage Example

// 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()
);

Request Transformers

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);
}

Composite and Delegating Handlers

Composite Access Denied Handler

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;
}

Usage Example

// 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
);

Exception Translation Patterns

Basic Exception Translation

// Basic setup for web applications
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
    new LoginUrlAuthenticationEntryPoint("/login")
);
filter.setAccessDeniedHandler(new AccessDeniedHandlerImpl("/access-denied"));

API Exception Translation

// Setup for REST APIs
ExceptionTranslationFilter apiFilter = new ExceptionTranslationFilter(
    new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
);
apiFilter.setAccessDeniedHandler(new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN));

Mixed Application Exception Translation

// 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);

Error Handling

Common exceptions in access control:

  • AccessDeniedException: Thrown when authenticated user lacks required permissions
  • AuthenticationException: Thrown when user is not authenticated
  • InsufficientAuthenticationException: Thrown when authentication level is insufficient
  • AuthenticationServiceException: Thrown for authentication service errors

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

docs

access-control.md

authentication.md

csrf.md

filter-chain.md

firewall.md

index.md

reactive.md

security-context.md

session-management.md

utilities.md

tile.json