Practical CSRF Token Implementation Guide
A Cross-Site Request Forgery (CSRF) attack occurs when an attacker tricks a user into performing unintended actions on a web application. For example, an attacker can create a malicious…
TechSilo
AI-assisted and human-curated
1. **The Risk**
A Cross-Site Request Forgery (CSRF) attack occurs when an attacker tricks a user into performing unintended actions on a web application. For example, an attacker can create a malicious website that sends a request to a user's bank website to transfer money. If the user is logged in to the bank website, the request will be executed, allowing the attacker to steal the user's money.
2. **The Vulnerability**
The following is an example of a vulnerable code in Python using the Flask framework:
from flask import Flask, request, session
app = Flask(__name__)
app.secret_key = 'secret_key'
@app.route('/transfer', methods=['POST'])
def transfer_money():
amount = request.form['amount']
recipient = request.form['recipient']
# Transfer money logic here
return 'Money transferred successfully'In this example, an attacker can create a malicious website with a form that sends a POST request to the /transfer endpoint, allowing them to transfer money from the user's account.
3. **The Fix**
To fix this vulnerability, we need to implement a CSRF token. Here's an example of how to do it using Flask-WTF:
from flask import Flask, request, session
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, SubmitField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
csrf = CSRFProtect(app)
class TransferForm(FlaskForm):
amount = StringField('Amount')
recipient = StringField('Recipient')
submit = SubmitField('Transfer')
@app.route('/transfer', methods=['GET', 'POST'])
def transfer_money():
form = TransferForm()
if form.validate_on_submit():
amount = form.amount.data
recipient = form.recipient.data
# Transfer money logic here
return 'Money transferred successfully'
return render_template('transfer.html', form=form)In this example, Flask-WTF generates a CSRF token and includes it in the form. When the form is submitted, the token is verified to ensure that the request came from the same origin.
4. **Checklist**
Before shipping your application, verify the following:
* CSRF token is generated: Ensure that a CSRF token is generated for each form.
* CSRF token is included in the form: Verify that the CSRF token is included in each form.
* CSRF token is verified on submission: Ensure that the CSRF token is verified when the form is submitted.
* CSRF token is unique per session: Verify that a new CSRF token is generated for each user session.
* CSRF token is properly configured: Ensure that the CSRF token is properly configured, including the secret key and token expiration.
5. **Tools**
The following tools can help automate CSRF token implementation:
* OWASP ZAP: A web application security scanner that can detect CSRF vulnerabilities.
* Burp Suite: A web application security testing tool that can help identify and exploit CSRF vulnerabilities.
* Flask-WTF: A Flask extension that provides CSRF protection and form handling.
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Environment Variable Management: Secure Secrets and Deployment Practices
Keep environment configuration safe across local development, CI, and production without leaking API keys into browser bundles or logs.
Read postPractical CORS Configuration Security Guide for APIs
Secure cross-origin browser requests with explicit origin allowlists, correct preflight handling, and credential rules.
Read postAPI Authentication Patterns: Sessions, Tokens, and Service Credentials
Compare session cookies, bearer tokens, OAuth, and API keys, with practical protections against token leakage and authorization mistakes.
Read postPractical XSS Protection in React: Escaping, Sanitization, and CSP
Prevent cross-site scripting in React by understanding text escaping, dangerous HTML injection, safe URL handling, and Content Security Policy.
Read postPreventing SQL Injection: Parameterized Queries and Safe Database Access
Learn how SQL injection works and how to prevent it using parameterized queries, least-privilege database accounts, and input validation.
Read post