How to do it: CSRF

This version shows the written code and the rendered result together using separated 3D cards for the trusted session, forged request, and defense.

Code first Rendered preview 3D cards
Safe lab preview: each card below teaches the structure of CSRF with a harmless mock interface and the exact code that renders each layer.

Layer 1 — trusted session

This is the logged-in state the browser already carries.

Rendered + Code
trusted banking page
Welcome back, Pola
The user is already signed in and the session cookie is still active.
Session cookie attached

Code for the logged-in state

Teach this as the normal trusted browser session.

<div class="sessionCard">
  <strong>Welcome back, Pola</strong>
  <div class="smallText">
    The browser is already logged in.
  </div>
  <div class="cookieChip">
    Session cookie attached
  </div>
</div>

Layer 2 — hidden forged request

This is the request quietly placed near the trusted session.

Rendered + Code
attacker page
Trusted bank tab
Hidden form
A forged request is prepared so the browser sends it with the existing cookie.
Auto-send request

Code for the forged form

Teach this as the hidden action that abuses the browser’s trust.

<form action="/transfer" method="POST">
  <input name="amount" value="5000">
  <input name="to" value="attacker">
</form>

// The browser may send its cookie automatically.

Layer 3 — automatic send

This explains the path the unwanted request takes once the page loads.

Rendered + Code
request flow preview
Victim browser
Hidden request
browser sends cookie too

Code that auto-submits the action

Use this to explain how the browser carries the session on its own.

// Safe mock example of automatic form submission
const form = document.querySelector('#demoForm');
if (form) {
  form.submit();
}

// The key lesson: the browser trusts the current session.

Defense — token check

This is the safe ending: the request needs a real anti-CSRF token to be accepted.

Rendered + Code
defense preview
Request blocked
No valid anti-CSRF token means the forged action is rejected.
Token required

Code that protects the action

Finish the lesson with the real protection check.

<input type="hidden" name="csrf_token" value="{{server_token}}">

if (request.token !== session.token) {
  rejectRequest();
}

// Same-site cookies add another layer of defense.