Nex.CSRF
(nex_core v0.4.3)
Copy Markdown
CSRF (Cross-Site Request Forgery) protection for Nex applications.
Uses signed tokens via Phoenix.Token — cryptographically verified across
request cycles without server-side session storage. Tokens are signed with a
secret derived from the application's secret key base.
How it works
- On page render (
GET),generate_token/0creates a signed token and stores it in the process dictionary for the current request. - The token is injected into
<head>as a<meta>tag and into every form automatically byNex.Handler. - On
POST/PUT/PATCH/DELETE,validate/1verifies the submitted token's cryptographic signature — no session lookup needed.
Usage
Everything is automatic. You do not need to call these functions manually. The framework handles injection and validation transparently.
Summary
Functions
Returns an HTML hidden input tag with the CSRF token.
Generates a new signed CSRF token for the current request.
Gets the current CSRF token, generating one if needed.
Returns a JSON string for hx-headers attribute with CSRF token.
Returns the meta tag for CSRF token (useful for JavaScript).
Checks if the request method requires CSRF validation.
Validates the CSRF token submitted with a request.
Functions
Returns an HTML hidden input tag with the CSRF token.
Generates a new signed CSRF token for the current request.
The token is a Phoenix.Token-signed value containing a random nonce.
It is stored in the process dictionary so helpers (csrf_input_tag/0 etc.)
can retrieve it without regenerating.
Gets the current CSRF token, generating one if needed.
Returns a JSON string for hx-headers attribute with CSRF token.
Returns the meta tag for CSRF token (useful for JavaScript).
Checks if the request method requires CSRF validation.
Validates the CSRF token submitted with a request.
Verifies the cryptographic signature of the token using Phoenix.Token.verify/4.
Returns :ok if valid, {:error, reason} otherwise.