Class CsrfProtection

java.lang.Object
io.karatelabs.http.CsrfProtection

public class CsrfProtection extends Object
CSRF (Cross-Site Request Forgery) protection utilities.

CSRF tokens are stored in the session and validated on state-changing requests (POST, PUT, PATCH, DELETE). The token can be sent via:

  • Form field: <input type="hidden" name="_csrf" th:value="csrf.token">
  • Request header: X-CSRF-Token: <token>
  • HTMX header: HX-CSRF-Token: <token> (sent automatically if configured)

Usage in templates:

 <form method="post">
     <input type="hidden" name="_csrf" th:value="csrf.token">
     ...
 </form>

 <!-- For HTMX requests, add to hx-headers or configure globally -->
 <meta name="csrf-token" th:content="csrf.token">
 <script>
     document.body.addEventListener('htmx:configRequest', (e) => {
         e.detail.headers['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').content;
     });
 </script>
 
  • Field Details

  • Constructor Details

    • CsrfProtection

      public CsrfProtection()
  • Method Details

    • generateToken

      public static String generateToken()
      Generate a new cryptographically secure CSRF token.
      Returns:
      a Base64-encoded random token
    • getOrCreateToken

      public static String getOrCreateToken(Session session)
      Get or create a CSRF token for the given session. If a token already exists in the session, it is returned. Otherwise, a new token is generated and stored.
      Parameters:
      session - the session to get/store the token in
      Returns:
      the CSRF token, or null if session is null
    • validate

      public static boolean validate(HttpRequest request, Session session)
      Validate a CSRF token from a request against the session token.
      Parameters:
      request - the HTTP request containing the token
      session - the session containing the expected token
      Returns:
      true if the token is valid, false otherwise
    • getTokenFromRequest

      public static String getTokenFromRequest(HttpRequest request)
      Extract CSRF token from request (header or form field).
      Parameters:
      request - the HTTP request
      Returns:
      the token if found, null otherwise
    • requiresValidation

      public static boolean requiresValidation(String method)
      Check if the request method requires CSRF validation.
      Parameters:
      method - the HTTP method
      Returns:
      true if CSRF validation is required
    • createTemplateToken

      public static CsrfProtection.CsrfToken createTemplateToken(Session session)
      Create a template-accessible object containing CSRF token information. This can be added to template variables as "csrf".
      Parameters:
      session - the session to get the token from
      Returns:
      a SimpleObject with token, headerName, and fieldName properties