Description
A browser may automatically send credentials such as cookies with a request its user did not intend. Protect routes that change data before they act with those credentials.
Potential impact
An unwanted request can modify or delete data and invoke account or administrative actions available to the signed-in user.
Remediation
Validate CSRF tokens on state-changing requests and reject untrusted origins on the server. Keep GET free of state changes. Use HTTPS and an appropriate SameSite cookie setting alongside these checks.
Examples
Django
A Django view can be protected by CsrfViewMiddleware without a local decorator. The first excerpt assumes no such protection is active.
Before
# Unsafe Django code
from django.http import HttpResponse
def my_view(request):
if request.method == 'POST':
# Process the request without CSRF validation
return HttpResponse("Request processed")
After
# Safe Django code
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def my_view(request):
if request.method == 'POST':
# Process the request after validating the CSRF token
return HttpResponse("Request processed")
Explanation:
- Before: This view handles POST without its own token check.
- After:
@csrf_protectadds token validation to the view.
Flask
For Flask, set the your_secret_key environment variable to a strong secret before startup. Protected forms and AJAX requests must supply the CSRF token.
Before
# Unsafe Flask code
from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['POST'])
def submit():
# Process the request without CSRF validation
return "Request processed"
After
# Safe Flask code
import os
from flask import Flask, request
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv("your_secret_key").encode()
csrf = CSRFProtect(app)
@app.route('/submit', methods=['POST'])
def submit():
# Process the request after validating the CSRF token
return "Request processed"
Explanation:
- Before: This POST route has no CSRF validation.
- After:
CSRFProtect(app)enables Flask-WTF token checks for the application.
FastAPI
The FastAPI examples assume a state-changing route with cookie authentication. Authenticate the user and authorize the operation separately.
Before
# Unsafe FastAPI code
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/submit")
async def submit(request: Request):
# Process the request without CSRF validation
return {"message": "Request processed"}
After
# Safe FastAPI code
from fastapi import FastAPI, Request, HTTPException
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
# Configure trusted hosts
app.add_middleware(
TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"]
)
@app.post("/submit")
async def submit(request: Request):
origin = request.headers.get('origin')
if origin not in ["https://example.com", "https://www.example.com"]:
raise HTTPException(status_code=403, detail="Invalid origin")
# Process the request
return {"message": "Request processed"}
Explanation:
- Before: The first route accepts POST without verifying a token or the request’s origin.
- After: The second route returns
403ifOriginis missing or outside the allow-list.TrustedHostMiddlewarechecks the destinationHost, a separate control.