What is CSRF?
The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?
It's a way that an attacker can potentially hijack sessions without even knowing session tokens.
Scenario:
- Visit your bank's site, log in.
- Then visit the attacker's site (e.g. sponsored ad from an untrusted organization).
- Attacker's page includes form with same fields as the bank's "Transfer Funds" form.
- Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account.
- Attacker's page includes Javascript that submits form to your bank.
- When form gets submitted, browser includes your cookies for the bank site, including the session token.
- Bank transfers money to attacker's account.
- The form can be in an iframe that is invisible, so you never know the attack occurred.
- This is called Cross-Site Request Forgery (CSRF).
CSRF solution:
- Server can mark forms that came from the server itself
- Every form must contain an additional authentication token as a hidden field.
- Token must be unpredictable (attacker can't guess it).
- Server provides valid token in forms in its pages.
- Server checks token when form posted, rejects forms without proper token.
- Example token: session identifier encrypted with server secret key.
- Rails automatically generates such tokens: see the authenticity_token input field in every form.