CSRF Protection

Cross-Site Request Forgery (CSRF) is an attack where another website makes a visitor’s browser send a request to yours, for example a hidden form that posts to /blog/delete/.... If the browser sends your login cookie with it, the request runs as the logged-in user, without them knowing.

What’s already in place#

The application is already well protected, as explained in the Login with JWT Token section:

  • The login cookie is SameSite=Lax, so browsers don’t send it with forms submitted from other websites.
  • Every change is made with POST, never GET, so links and images can’t change anything.

Defence in depth#

SameSite has one gap: it’s about sites, not exact addresses. blog.example.com and shop.example.com are the same site, so if your application shares a domain with something you don’t fully control, such as a subdomain hosted elsewhere, a page there could still send forms with the cookie.

Browsers say where a request comes from, in two headers that web pages can’t change: Origin, the scheme and address of the page that sent it, and Sec-Fetch-Site, which is cross-site for requests from another site. A short middleware in main.py refuses any state-changing request that comes from somewhere else:

main.pypython
from urllib.parse import urlsplit  # NEW

from fastapi.responses import PlainTextResponse  # NEW
main.pypython
# CSRF defence in depth: refuse state-changing requests sent from another website
UNSAFE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}

@main_app.middleware("http")
async def check_request_origin(request: Request, call_next):
    if request.method in UNSAFE_METHODS:
        origin = request.headers.get("origin")
        cross_site = request.headers.get("sec-fetch-site") == "cross-site"
        wrong_origin = origin is not None and urlsplit(origin).netloc != request.headers.get("host")
        if cross_site or wrong_origin:
            return PlainTextResponse("Cross-site request refused", status_code=403)
    return await call_next(request)
  • Only POST, PUT, PATCH and DELETE are checked, since GET requests never change anything.
  • The Origin header’s address must match the Host the request was sent to. Behind OpenShift’s router, both are the public address.
  • Requests with neither header, such as the Stripe webhook, curl or the tests, aren’t affected: they don’t come from a browser, so they can’t carry a visitor’s cookie on another site’s behalf.

This is the approach recommended by the OWASP CSRF Prevention Cheat Sheet for applications that already use SameSite cookies, and it needs no changes to any form. (The alternative, a secret token in every form, means changing every template and view. Packages such as fastapi-csrf-protect do that, if you need it.)

You can check it with curl, pretending to be a form on another site:

curl -i -X POST http://localhost:8000/contact -H 'Origin: https://evil.example' -d name=x
HTTP/1.1 403 Forbidden

Cross-site request refused
Code

This, and the SEO changes, are on the example code’s main branch, tagged appendix-extras, with tests in test_extras.py.