Package io.karatelabs.http
Class CsrfProtection
java.lang.Object
io.karatelabs.http.CsrfProtection
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>
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classCSRF token object exposed to templates. -
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic CsrfProtection.CsrfTokencreateTemplateToken(Session session) Create a template-accessible object containing CSRF token information.static StringGenerate a new cryptographically secure CSRF token.static StringgetOrCreateToken(Session session) Get or create a CSRF token for the given session.static StringgetTokenFromRequest(HttpRequest request) Extract CSRF token from request (header or form field).static booleanrequiresValidation(String method) Check if the request method requires CSRF validation.static booleanvalidate(HttpRequest request, Session session) Validate a CSRF token from a request against the session token.
-
Field Details
-
SESSION_KEY
Session key where the CSRF token is stored- See Also:
-
FORM_FIELD_NAME
Default form field name for CSRF token- See Also:
-
HEADER_NAME
Default HTTP header name for CSRF token- See Also:
-
HTMX_HEADER_NAME
HTMX-specific header name- See Also:
-
-
Constructor Details
-
CsrfProtection
public CsrfProtection()
-
-
Method Details
-
generateToken
Generate a new cryptographically secure CSRF token.- Returns:
- a Base64-encoded random token
-
getOrCreateToken
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
Validate a CSRF token from a request against the session token.- Parameters:
request- the HTTP request containing the tokensession- the session containing the expected token- Returns:
- true if the token is valid, false otherwise
-
getTokenFromRequest
Extract CSRF token from request (header or form field).- Parameters:
request- the HTTP request- Returns:
- the token if found, null otherwise
-
requiresValidation
Check if the request method requires CSRF validation.- Parameters:
method- the HTTP method- Returns:
- true if CSRF validation is required
-
createTemplateToken
Create a template-accessible object containing CSRF token information. This can be added to template variables as "csrf".Returns
nullwhengetOrCreateToken(Session)would yieldnull(i.e. the session isnullor temporary). Returningnull— rather than a wrapper around anulltoken — lets templates useth:if="context.csrf"as the natural presence check and skip rendering CSRF-related markup (e.g. a<meta name="csrf-token">tag) for anonymous visitors. Otherwise the wrapper is truthy while its inner token is empty, producing markup that exposes no usable token.- Parameters:
session- the session to get the token from- Returns:
- a
CsrfProtection.CsrfTokenwith token / headerName / fieldName properties, ornullif no token is available
-