← Lessons

quiz vs the machine

Silver1080

Security

Cross Site Request Forgery CSRF

Why a logged in user can be tricked into making unwanted state changing requests.

4 min read · intro · beat Silver to climb

What CSRF Is

Cross Site Request Forgery tricks an authenticated user's browser into sending a state changing request the user never intended. Because browsers automatically attach cookies, a malicious page can submit a hidden form to your site and ride the victim's existing session.

Why It Works

  • The browser sends ambient credentials like session cookies with every request to a domain.
  • The target server cannot tell a genuine click from a forged one by cookies alone.
  • Only requests that change state, such as transfers or password changes, are valuable targets.

Defenses

  • Use a synchronizer token that the server issues and validates per session, unknown to other origins.
  • Set cookies with SameSite set to Lax or Strict so they are not sent on cross site requests.
  • Check the Origin or Referer header for sensitive actions.
  • Require re authentication for high risk operations.

Key idea

CSRF abuses automatically attached credentials, so defend state changing requests with anti forgery tokens and SameSite cookies.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does CSRF succeed against a logged in user?

2. Which cookie attribute helps prevent CSRF?