🛡️ CSRF Protection
❓ What is CSRF?
CSRF (Cross-Site Request Forgery) is an attack where a malicious actor tricks a user's browser into making an unwanted request to your website.
For example, a user is logged into their banking site, and an attacker submits a money transfer request on their behalf by embedding it on a third-party page.
Without CSRF protection, your forms and POST requests can become vulnerable to such attacks.
🔑 Why Use a CSRF Token?
A CSRF token is a unique string generated by the server and embedded in every form or request.
When the server receives a POST/PUT/PATCH/DELETE request, it checks whether the token matches the one it generated.
If the token is missing or invalid, the request is blocked. This prevents forged requests.
⚙️ How Protection Works in PageBlocks
PageBlocks includes CSRF protection by default via a dedicated middleware.
All POST, PUT, and DELETE requests are automatically checked for a valid CSRF token.
✅ GET requests do not require validation since they do not modify data.
📌 How to Add a CSRF Token
1️⃣ In a Meta Tag
The most universal method is to add the token to your template's <head>:
<meta name="csrf-token" content="{csrf_token}">{csrf_token} is a function for the Fenom templating engine.
This tag is automatically picked up by all pbFetch AJAX requests—the X-CSRF-TOKEN header will be included in POST/PUT/DELETE requests.
2️⃣ In Each Form
If you use traditional <form> submissions (not just AJAX), include the CSRF token as a hidden field:
<form method="POST" action="/profile/update">
{csrf()}
<!-- Other fields -->
<button type="submit">Save</button>
</form>or
<form method="POST" action="/profile/update">
<input type="hidden" name="_token" value="{csrf_token}">
<!-- Other fields -->
<button type="submit">Save</button>
</form>⚙️ How It Works in Code
- PageBlocks automatically applies CSRF middleware to all routes requiring protection.
- When a POST/PUT/DELETE request is received, the middleware checks the token from either the
X-CSRF-TOKENheader or the_tokenhidden field. - If the token is missing or invalid, a
403 Forbiddenerror is returned.
✅ Summary
- CSRF protection is mandatory for all applications handling authenticated actions.
- Add
<meta name="csrf-token" ...>and hidden fields to forms—it's simple and reliable. - The entire process is automated via middleware—you just need to remember to include the token.
Use CSRF tokens—and your project will be protected against one of the most common web vulnerabilities!