Cross-Site Request Forgery (CSRF) Tutorial
Introduction
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious site tricks a user into performing actions on another site where the user is authenticated. This can lead to unauthorized actions being executed on the user's behalf, potentially compromising sensitive data and accounts.
How CSRF Works
CSRF exploits the trust that a site has in a user's browser. If a user is logged into a website, their browser will include their session cookie with any request made to that site. An attacker can create a fake form on their own site that submits a request to the targeted site, using the user's session cookie to authenticate the request.
Preventing CSRF in Django
Django provides built-in protection against CSRF attacks. This is achieved by using a CSRF token that must be included with any POST request. The token is unique to the user's session and the form being submitted.
Example: CSRF Protection in Django
Let's consider a simple example of a Django form that is protected against CSRF attacks.
views.py
from django.shortcuts import render from django.views.decorators.csrf import csrf_protect @csrf_protect def my_view(request): if request.method == 'POST': # Process the form data pass return render(request, 'my_template.html')
my_template.html
In this example, the @csrf_protect
decorator ensures that the view only accepts POST requests that contain a valid CSRF token. The {% csrf_token %}
template tag adds a hidden input field with the CSRF token to the form.
Testing CSRF Protection
To test CSRF protection, you can try submitting the form without including the CSRF token or by using a different token. Django will respond with a "403 Forbidden" error, indicating that the request was not authorized.
Conclusion
CSRF is a serious security vulnerability that can lead to unauthorized actions on a user's behalf. By using Django's built-in CSRF protection mechanisms, you can effectively prevent CSRF attacks and ensure the security of your web applications.