CSRF
Definition
Cross-Site Request Forgery (CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions they do not intend to perform. This is achieved by exploiting the trust that a web application has in the user’s browser, allowing unauthorized commands to be transmitted from a user that the web application trusts. CSRF attacks are typically executed by tricking the user into submitting a malicious request, often via a link or a form embedded in a webpage controlled by the attacker.
Secure Settings Example
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>
# Example in a Flask application
from flask import Flask, request, session, abort
import secrets
app = Flask(__name__)
app.secret_key = 'your_secret_key'
@app.before_request
def csrf_protect():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('csrf_token'):
abort(403)
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = secrets.token_hex(16)
return session['_csrf_token']
app.jinja_env.globals['csrf_token'] = generate_csrf_token
Insecure Settings Example
<form action="/transfer" method="POST">
<!-- No CSRF token included -->
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>
# Example in a Flask application without CSRF protection
from flask import Flask, request
app = Flask(__name__)
@app.route('/transfer', methods=['POST'])
def transfer():
# No CSRF token validation
# Process the transfer
return "Transfer completed"