Let's examine the creation, validation, and verification of CSRF tokens in a typical web application procedure. Additionally, I'll give examples for two well-known frameworks: Django and Express.
What is a CSRF Token?
A unique, confidential, and unpredictable value produced by the server-side application is known as a CSRF (Cross-Site Request Forgery) token. Its main objective is to stop fraudulent websites from requesting things on behalf of users without authorization.
Here's a step-by-step breakdown of how CSRF tokens work:
Token Generation:
- The server creates a random, distinct, and secret CSRF token whenever a user requests a form or a page that will ultimately result in a sensitive action (such as sending money or changing a profile).
- This token is frequently saved as a secure cookie (with flags like HttpOnly and Secure set) or in the user's session.
Token Inclusion in Form/Page:
- The form or page contains the generated CSRF token embedded as a:
Hidden form field (e.g., <input type="hidden" name="csrf_token" value="...">).
- JavaScript variables or meta tags are less popular but still useful.
User Submits the Form:
The form data, including the CSRF token, is sent to the server by the browser when the user submits the form.
Token Validation:
- The server compares the given CSRF token with the one kept in the user's session or secure cookie after receiving the request.
- The request is deemed valid and the action is carried out if the tokens match.
- The server blocks the possible CSRF attack by rejecting the request if the tokens are absent or don't match.
Examples in Popular Frameworks
1. Django (Python)
In Django, CSRF protection is enabled by default for all forms.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
2. Express.js (Node.js) with CSURF middleware
For Express.js, you can use the csurf middleware to handle CSRF protection:
const express = require('express');
const csrf = require('csurf');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(csrf());
app.get('/form', (req, res) => {
res.render('form', { csrfToken: req.csrfToken() });
});
app.post('/submit', (req, res) => {
// If we reach this point, the CSRF token has been validated
// Process the form submission
});