Security Filters and Interceptors

About

Security Filters and Interceptors are two core components in Spring Security that handle authentication, authorization, and request processing at different stages.

Component

Purpose

Executes Before/After

Security Filters

Process incoming requests for authentication, authorization, CSRF protection, CORS, etc.

Before the request reaches the controller

Security Interceptors

Perform security-related checks at the method and API level.

Before/After method execution

Security Filters in Spring Security

How Filters Work in Spring Security

Spring Security uses the Servlet Filter chain to intercept requests before they reach the application.

Security Filter Chain Overview

  1. The Http request enters the application.

  2. Spring Security filters the request based on authentication and authorization rules.

  3. If the request is valid, it is passed to the next filter.

  4. If authentication/authorization fails, the request is rejected.

  5. Once all filters are executed, the request is handed to the application.

Core Security Filters in Spring Security

Spring Security applies multiple filters in a specific order:

Filter Name

Purpose

ChannelProcessingFilter

Enforces HTTPS and security constraints.

WebAsyncManagerIntegrationFilter

Integrates Spring Security with asynchronous requests.

SecurityContextPersistenceFilter

Restores SecurityContext between requests (session-based security).

HeaderWriterFilter

Adds security headers (e.g., X-Frame-Options, Content-Security-Policy).

CorsFilter

Handles CORS policies.

CsrfFilter

Prevents Cross-Site Request Forgery (CSRF) attacks.

LogoutFilter

Manages user logout functionality.

UsernamePasswordAuthenticationFilter

Handles form-based authentication (processes username/password login).

DefaultLoginPageGeneratingFilter

Generates a default login page if none is provided.

BasicAuthenticationFilter

Handles HTTP Basic Authentication.

BearerTokenAuthenticationFilter

Processes JWT and OAuth2 token-based authentication.

RequestCacheAwareFilter

Saves unauthorized requests and redirects after authentication.

SecurityContextHolderAwareRequestFilter

Wraps requests to provide Spring Security capabilities.

AnonymousAuthenticationFilter

Assigns an anonymous authentication token to unauthenticated users.

SessionManagementFilter

Controls session security policies (concurrent session control, timeout).

ExceptionTranslationFilter

Converts security exceptions into HTTP responses.

FilterSecurityInterceptor

Final authorization filter that enforces security rules.

How Spring Security Applies Filters

Spring Security automatically registers filters based on the configuration.

Example: Manually Registering a Custom Security Filter

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated());

        return http.build();
    }
}
  • addFilterBefore() inserts a custom filter before UsernamePasswordAuthenticationFilter.

  • Custom filters can be used for logging, request validation, or additional security checks.

Custom Security Filter Implementation

A custom security filter can inspect or modify requests before authentication.

Example: Custom Security Filter

public class CustomFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // Custom logic before processing authentication
        System.out.println("Custom Filter Executed: " + request.getRequestURI());

        filterChain.doFilter(request, response); // Continue the filter chain
    }
}
  • OncePerRequestFilter ensures the filter runs once per request.

  • The filter logs requests before processing.

Security Interceptors in Spring Security

Security Interceptors enforce method-level security in Spring Security. They work inside the application, rather than at the filter level.

Types of Security Interceptors

Interceptor

Purpose

FilterSecurityInterceptor

Ensures authorization at the filter level.

MethodSecurityInterceptor

Enforces security on methods using annotations.

AspectJMethodSecurityInterceptor

Enables AspectJ-based security for non-Spring-managed beans.

Method Security with Security Interceptors

Using @PreAuthorize for Authorization

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long userId) {
    // Only ADMIN can delete a user
}
  • @PreAuthorize is evaluated by MethodSecurityInterceptor before executing the method.

Using @PostAuthorize for Authorization

@PostAuthorize("returnObject.owner == authentication.name")
public Order getOrder(Long id) {
    return orderRepository.findById(id).orElseThrow();
}
  • The method executes first, and then authorization is checked after the result is returned.

How Spring Security Configures Interceptors

Spring Security automatically registers interceptors when method-level security is enabled.

@Configuration
@EnableMethodSecurity
public class SecurityConfig {
}
  • @EnableMethodSecurity enables MethodSecurityInterceptor for method-level security.

Last updated

Was this helpful?