Example
Adding a Custom Filter for Request Validation
Use Case
We need to validate API requests for a custom security header before authentication.
If the request is invalid, reject it before it reaches the authentication filter.
Implementation
We create a custom filter that checks for a mandatory security header.
Custom Filter
@Component
public class CustomRequestValidationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String securityHeader = request.getHeader("X-SECURITY-HEADER");
if (securityHeader == null || !securityHeader.equals("EXPECTED_VALUE")) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid security header");
return;
}
filterChain.doFilter(request, response);
}
}Register the Filter in Security Configuration
Explanation
The CustomRequestValidationFilter checks if the request contains a security header.
If the header is missing or invalid, the request is rejected before authentication.
Otherwise, the request proceeds to the UsernamePasswordAuthenticationFilter.
Implementing JWT Authentication with a Custom Filter
Use Case
You need to authenticate users using JWT tokens instead of sessions.
The filter extracts the token, verifies it, and sets the authentication in the SecurityContext.
Implementation
JWT Utility Class
JWT Authentication Filter
Register the JWT Filter in Security Configuration
Explanation
Extracts JWT from the
Authorizationheader.Validates the token and extracts the username.
Loads the user details and sets the authentication.
Replaces default session-based authentication with token-based authentication.
Using Multiple Authentication Mechanisms (JWT + Username/Password + API Keys)
Use Case
Some endpoints require JWT-based authentication.
Some endpoints allow Username/Password login.
Some internal API calls use API keys.
Implementation
Custom API Key Filter
Register Multiple Authentication Mechanisms
Explanation
The API Key filter runs before basic authentication to check if an API key is present.
If an API key is valid, a user with the ROLE_API is authenticated.
The JWT authentication filter runs before username/password authentication to check for a valid JWT.
The authentication order is:
API Key Authentication
JWT Authentication
Username/Password Authentication
Handling Access Control Based on Request Attributes
Use Case
We want to restrict access based on a custom request parameter.
Users can access different resources based on a custom header value.
Implementation
Custom Access Filter
Register in Security Configuration
Explanation
This filter ensures that only requests with "X-Client-Type: INTERNAL" are processed.
If the header is missing or incorrect, the request is blocked.
Enforcing Custom IP Whitelisting Using a Security Filter
Use Case
Only requests from whitelisted IP addresses are allowed to access sensitive endpoints like /admin/**.
Implementation
Register Filter Before Authorization
Execution Flow
IP Whitelist Filter runs first → If IP is not in the whitelist, request is blocked.
If IP is allowed, authentication proceeds.
Role-based access control is enforced for admin routes.
Implementing CSRF Protection Only for Certain Requests
Use Case
The app disables CSRF globally but enables it only for specific endpoints like POST requests to /secure/**.
Implementation
Custom CSRF Filter
Register the Filter
Execution Flow
CSRF is disabled globally but enforced for specific requests (
/secure/**).If the request is a
POSTto/secure/**, the filter checks for a valid CSRF token.If the token is missing or incorrect, the request is blocked (403 Forbidden).
Custom Filter for Logging and Rate Limiting
Use Case
Create a custom filter that logs requests and implements rate limiting before authentication occurs. Place before UsernamePasswordAuthenticationFilter.
Implementation
Registering the Custom Filter
Explanation
Logs every incoming request along with the client IP and requested path.
Implements rate limiting to prevent abuse.
Rejects requests with
429 Too Many Requestsif the IP exceeds the allowed limit.Continues with the filter chain if the request is within the limit.
Rate Limiting with Time Based Expiry
Use Case
Create a custom filter that implements rate limiting before authentication occurs. Each IP entry automatically expires after 24 hours.
Solution 1: ConcurrentHashMap with Expiry
Explanation
Each IP is tracked in a
RequestInfoobject that stores:The count of requests.
The timestamp of the first request.
If an IP exceeds the limit in 24 hours, it gets blocked.
Once 24 hours pass since the first request, the count automatically resets.
This method ensures that different IPs reset independently rather than at a fixed global interval.
Solution 2: Using Caffeine Cache (Auto-Expiry)
Use Caffeine Cache with an automatic expiration policy to reset the count per IP after 24 hours.
Add Dependency
Explanation
Uses Caffeine Cache to store IP request counts.
Each IP's request count automatically expires after 24 hours.
No need for a scheduled task; expiration is handled internally.
More memory-efficient than
ConcurrentHashMap.
Last updated