Cross-Site Request Forgery (CSRF)

A browser can attach a session cookie automatically. For actions such as changing a recovery email, the server needs evidence that the request came through the intended application flow.

On this page

Bind a form submission to its session

CSRF occurs when another site causes a signed-in browser to send an unwanted action. Use the framework’s CSRF middleware for cookie-authenticated changes. In this template the server inserts a session-bound token. The middleware verifies it before the handler saves a change. Keep the token out of URLs and logs.

<form action="/settings/email" method="post">
  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
  <label>New email <input type="email" name="email" required></label>
  <button>Save email</button>
</form>

Keep reads and changes separate

Keep GET read-only. Verify the CSRF token on state-changing requests and apply relevant Origin checks. SameSite cookies add protection. A request that fails verification must leave the stored record untouched.

GET  /settings/email    Show the form
POST /settings/email    Verify session and CSRF token, then validate the change
Missing token           Reject the request and preserve the current email

Official references