Working of CSRF Protection
To understand this let us take an example. Suppose you are logged into the website. The attacker sends a link with the help of an email, chat, or with the use of sms. The link contains the request which the attacker wants to be performed. As the user is already authenticated on the website the request is completed when he clicks on the link. This type of request is very dangerous as it may take complete access to the data and other harmful actions may be performed such as transfer of funds, change of email and so on.
Token Generation
When a user logs in or starts a session, Django generates a random and unique CSRF token for that session. This token is usually a long string of characters. This token is associated with the user’s session and stored on the server.
CsrfViewMiddleware
sends this cookie with the response whenever django.middleware.csrf.get_token()
is called. It can also send it in other cases. For security reasons, the value of the secret is changed each time a user logs in.
Token Inclusion in Forms
When Django renders an HTML form using a template, it includes the CSRF token using the {% csrf_token %}
template tag. The CSRF token should be added as a hidden input field in the form.
Example
HTML
< form method = "post" > {% csrf_token %} <!-- Other form fields here --> < button type = "submit" >Submit</ button > </ form > |
Token Validation on Submission
When the user submits the form, the CSRF token is sent along with the request, either as a POST parameter or a request header (e.g., X-CSRFToken
). The token is extracted from the request by the server. It is then verified that if this token (received in request) matches with the token which is linked with the user’s session. If the token matches, the request is considered as valid and we can proceed with it. If they don’t match, then the server interprets it as it may be a CSRF attack and rejects the request.
CSRF token in Django
Django provides a feature known as a CSRF token to get away from CSRF attacks that can be very dangerous. when the session of the user starts on a website, a token is generated which is then cross-verified with the token present with the request whenever a request is being processed.
Contact Us