CSRF Protection — Complete Anti-Forgery Patterns Guide
In this tutorial, you will learn about CSRF Protection. We cover key concepts, practical examples, and best practices to help you master this topic.
Cross-Site Request Forgery (CSRF) protection ensures that requests to state-changing endpoints originate from your application, not from a malicious site exploiting an authenticated session.
What You'll Learn
You'll learn CSRF protection strategies specific to different authentication patterns including sessions, tokens, and cookies.
Why It Matters
CSRF is particularly dangerous with cookie-based authentication because browsers automatically include cookies in cross-origin requests. Token-based auth is immune but cookie-based auth must implement CSRF protection.
Real-World Use
An admin panel uses session auth with CSRF tokens. The API generates a token on login, includes it in forms, and validates it on every POST/PUT/DELETE request. An attacker's forged form is rejected because it lacks the token.
Implementation
import secrets
from flask import Flask, request, jsonify, session
app = Flask(__name__)
@app.route("/api/csrf-token")
def get_csrf_token():
if "csrf_token" not in session:
session["csrf_token"] = secrets.token_hex(32)
return jsonify({"csrf_token": session["csrf_token"]})
@app.route("/api/transfer", methods=["POST"])
def transfer():
csrf_token = request.headers.get("X-CSRF-Token")
if not csrf_token or csrf_token != session.get("csrf_token"):
return jsonify({"error": "CSRF validation failed"}), 403
session["csrf_token"] = secrets.token_hex(32)
return jsonify({"message": "Transfer completed"})
Common Mistakes
| Mistake | Fix |
|---|---|
| CSRF protection on token-based auth | Not needed if using Bearer tokens in headers |
| Same token for entire session | Rotate token after each state change |
| Token in URL parameter | Visible in logs and Referer header |
| No SameSite cookie attribute | Set SameSite=Strict on session cookies |
| Skipping CSRF on GET requests | GET should be idempotent; protect all mutations |
What's Next
Complete the authentication patterns by building the Authentication Project.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro