Package filter

Class CSRFProtectionFilter

java.lang.Object
filter.CSRFProtectionFilter
All Implemented Interfaces:
javax.servlet.Filter

public class CSRFProtectionFilter extends Object implements 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 Details

  • 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 interface javax.servlet.Filter
      Parameters:
      request - the servlet request
      response - the servlet response
      chain - the filter chain
      Throws:
      IOException - if an I/O error occurs
      javax.servlet.ServletException - if a servlet error occurs
    • isStaticResource

      private boolean isStaticResource(String path)
      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

      private String 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 interface javax.servlet.Filter
      Parameters:
      filterConfig - the filter configuration
    • destroy

      public void destroy()
      Cleans up resources when filter is destroyed.
      Specified by:
      destroy in interface javax.servlet.Filter