CSRF (Cross-Site Request Forgery): What is it?
Définition
CSRF (Cross-Site Request Forgery) is a web attack that forces an authenticated user to execute unwanted actions on a trusted site. Django natively includes a CSRF protection middleware based on synchronised tokens, providing robust defence against this attack vector listed in the OWASP Top 10.What is CSRF (Cross-Site Request Forgery)?
Cross-Site Request Forgery, abbreviated CSRF (sometimes also called XSRF or "sea-surf"), is a web attack that exploits the trust a site places in the user's browser. In practice, an attacker creates a malicious page containing a form or link that automatically submits a request to a site where the victim is authenticated. Since the browser automatically sends session cookies with every request, the target site cannot distinguish a legitimate request from a forged one.
Imagine a user logged into their online banking application. Without CSRF protection, an attacker could embed an invisible form in an email or website that submits a transfer order to their own account. The victim's browser would execute this request with valid session cookies, and the bank would process the transaction as legitimate. CSRF is classified among the major risks by OWASP (Open Web Application Security Project) and regularly features in the Top 10 most critical web vulnerabilities.
This attack is particularly insidious because it requires no password theft or code injection into the target application. It solely exploits the cookie-based authentication mechanism, which remains the standard for most web applications. In the context of GDPR applicable in Belgium and Europe, a CSRF vulnerability can lead to personal data leaks and expose the company to significant penalties.
Why CSRF matters
Protection against CSRF is a fundamental pillar of modern web application security. Its importance manifests across several dimensions critical to businesses.
- User action integrity: without CSRF protection, any action a user can perform (modifying a profile, placing an order, deleting data) can be triggered without their knowledge by an attacker.
- GDPR compliance: the European regulation requires appropriate technical measures to protect personal data. An application vulnerable to CSRF does not meet this obligation, exposing the company to fines of up to 4% of annual turnover.
- User trust: an exploited vulnerability destroys user trust in the platform. In a B2B context, this can compromise lasting business relationships.
- OWASP Top 10 ranking: CSRF is among the most commonly exploited vulnerabilities according to OWASP, making it a prime target for automated attackers and scanning scripts.
- Native Django protection: the Django framework, used by Kern-IT, includes CSRF protection enabled by default via the CsrfViewMiddleware, significantly reducing risk for applications built with this stack.
How it works
The CSRF attack mechanism relies on the automatic behaviour of web browsers that attach authentication cookies to every request to a given domain. The attacker creates a booby-trapped page containing an HTML form whose action attribute points to the target URL, for example <form action="https://target-app.be/transfer" method="POST">. Hidden form fields pre-fill the parameters of the malicious request, and a JavaScript script automatically submits this form as soon as the page loads.
The most widespread protection against CSRF is the Synchronizer Token Pattern. The server generates a unique random token for each user session and embeds it in every HTML form as a hidden field. Upon submission, the server verifies that the received token matches the one stored in the session. An attacker cannot guess this token because they cannot read the content of pages from the target domain (Same-Origin Policy).
Django implements this protection via the CsrfViewMiddleware middleware and the {% csrf_token %} template tag. Every POST form in a Django template must include this tag, which generates a hidden field containing the CSRF token. For AJAX requests, Django uses a CSRF cookie (csrftoken) that JavaScript can read and send back in an HTTP header (X-CSRFToken). Complementary protections include the SameSite attribute on session cookies and verification of the Origin or Referer header.
Concrete example
At Kern-IT, all our Django applications benefit from CSRF protection enabled by default. In a business platform project for a real estate (proptech) client, users manage properties and financial transactions via a web interface. Every form, whether for creating a property listing, validating an offer, or modifying bank details, is protected by a CSRF token automatically generated by Django.
For JavaScript interactions with our REST API, we configured automatic retrieval of the CSRF token from the cookie and its injection into the headers of every AJAX request via an Axios interceptor. This transparent approach ensures protection without impacting user experience or complicating frontend code. During the security audit, penetration tests confirmed the impossibility of exploiting CSRF thanks to this native Django protection layer.
Implementation
- Enable the CSRF middleware: verify that
django.middleware.csrf.CsrfViewMiddlewareis present in the MIDDLEWARE list of your settings.py file. It is enabled by default in every Django installation. - Include the token in forms: add
{% csrf_token %}inside every<form>tag that uses the POST method in your Django templates. - Configure AJAX requests: for JavaScript calls, retrieve the csrftoken cookie and send it in the X-CSRFToken header. Django provides detailed documentation for jQuery, Fetch API, and Axios.
- Enable SameSite on cookies: configure
SESSION_COOKIE_SAMESITE = "Lax"andCSRF_COOKIE_SAMESITE = "Lax"in your settings for an additional protection layer. - Configure CSRF_TRUSTED_ORIGINS: explicitly list authorised origins in
CSRF_TRUSTED_ORIGINSfor multi-domain deployments or behind a reverse proxy. - Test with OWASP tools: use OWASP ZAP or Burp Suite to verify that your CSRF protection is effective on all sensitive routes of the application.
Associated technologies and tools
- Django CsrfViewMiddleware: Django's native middleware that automatically manages the generation and verification of CSRF tokens.
- OWASP ZAP: open-source automated security testing tool, capable of detecting forms unprotected against CSRF.
- Burp Suite: professional web security testing platform with dedicated modules for detecting CSRF vulnerabilities.
- SameSite Cookies: cookie attribute supported by modern browsers that limits the sending of cookies in cross-origin requests.
- Content Security Policy (CSP): HTTP header that reduces the attack surface by limiting authorised content sources.
- Helmet.js / django-csp: libraries to easily configure HTTP security headers in Node.js and Django applications.
Conclusion
CSRF remains a real threat to web applications that do not implement adequate protections. The good news for Django developers is that the framework provides robust protection enabled by default, provided best practices are followed: include the CSRF token in every form, correctly configure AJAX requests, and maintain session cookies with appropriate security attributes. At Kern-IT, we systematically integrate these protections into our web applications and business platforms, complemented by regular security audits aligned with OWASP recommendations and GDPR requirements.
Never disable CSRF protection with the @csrf_exempt decorator for convenience. If your API needs to accept cross-origin requests, use JWT token authentication combined with django-cors-headers to manage CORS permissions securely instead.