Origin validation errors

Apply appropriate origin validation and CSRF protection to requests whose credentials are sent automatically by the browser.

Description

A request from another site can change a user’s account if the browser sends authentication cookies and the server lacks CSRF protection. The Origin header identifies the requesting origin. Clients outside the browser can supply that header themselves.

Potential impact

Unwanted requests can alter data or expose sensitive information by changing sharing or forwarding settings.

Remediation

  • Validate a CSRF token on state-changing requests that use cookie authentication. If you check the origin, match the scheme, host and port against an exact allow-list and define how to handle a missing Origin or a null origin.
  • Use CORS to limit which sites can read responses. Authenticate the user and authorize the requested operation on the server.

Examples

These excerpts assume the server separately authenticates the user by cookie and checks permission for the operation. Send a valid CSRF token with POST requests to the protected Django and Flask handlers.

Django

Before

python
# 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

python
# 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")

@csrf_protect applies CSRF validation to this view. If CsrfViewMiddleware is active globally, the earlier view may already be protected without the decorator.

Flask

Before

python
# 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

python
# 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():
    return "Request processed"

Set the your_secret_key environment variable to an unpredictable secret before startup. CSRFProtect(app) checks the token on this POST request.

FastAPI

Before

python
# 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

python
# 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"}

The FastAPI handler returns HTTP 403 for a missing or unlisted Origin. TrustedHostMiddleware checks the destination Host separately. This example does not validate a CSRF token.

References