Package filter
Class CSRFProtectionFilter
java.lang.Object
filter.CSRFProtectionFilter
- All Implemented Interfaces:
javax.servlet.Filter
Filter that protects against Cross-Site Request Forgery (CSRF) attacks.
Generates and validates CSRF tokens for POST requests.
- Author:
- TAMIL MUGHILAN
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final String
private static final String
private SecureRandom
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
destroy()
Cleans up resources when filter is destroyed.void
doFilter
(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain) Processes requests to validate CSRF tokens and generate new ones.private String
Generates a secure random CSRF token.void
init
(javax.servlet.FilterConfig filterConfig) Initializes the filter when application starts.private boolean
isStaticResource
(String path) Checks if the requested path is a static resource.
-
Field Details
-
CSRF_TOKEN_ATTR
- See Also:
-
CSRF_TOKEN_PARAM
- See Also:
-
secureRandom
-
-
Constructor Details
-
CSRFProtectionFilter
public CSRFProtectionFilter()
-
-
Method Details
-
doFilter
public void doFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain) throws IOException, javax.servlet.ServletException Processes requests to validate CSRF tokens and generate new ones. Blocks requests with invalid or missing CSRF tokens.- Specified by:
doFilter
in interfacejavax.servlet.Filter
- Parameters:
request
- the servlet requestresponse
- the servlet responsechain
- the filter chain- Throws:
IOException
- if an I/O error occursjavax.servlet.ServletException
- if a servlet error occurs
-
isStaticResource
Checks if the requested path is a static resource.- Parameters:
path
- the request path to check- Returns:
- true if it's a static resource, false otherwise
-
generateCSRFToken
Generates a secure random CSRF token.- Returns:
- a Base64 encoded CSRF token
-
init
public void init(javax.servlet.FilterConfig filterConfig) Initializes the filter when application starts.- Specified by:
init
in interfacejavax.servlet.Filter
- Parameters:
filterConfig
- the filter configuration
-
destroy
public void destroy()Cleans up resources when filter is destroyed.- Specified by:
destroy
in interfacejavax.servlet.Filter
-