CSRF Protection
Auto defense against Cross-Site Request Forgery attacks
CSRF (Cross-Site Request Forgery) is an attack where a malicious site uses the user's browser to send forged requests to another site.
Rails auto-defense:
1. <%= csrf_meta_tags %> โ inserts CSRF token in HTML <head>
2. form_with โ auto-adds authenticity_token hidden field to forms
3. protect_from_forgery with: :exception โ raises exception on token mismatch
How it works:
Server stores CSRF token in session
All form/AJAX requests include this token
Server compares request token with session token
Mismatch โ 422 Unprocessable Entity
Notes:
API apps use
protect_from_forgery with: :null_sessionAJAX requests send token via
X-CSRF-TokenheaderTurbo automatically includes CSRF token
Key Points
protect_from_forgery auto-configured in ApplicationController (Rails default)
csrf_meta_tags inserts token in <head>
form_with auto-adds hidden authenticity_token field
Server validates tokens for POST/PATCH/DELETE requests
ActionController::InvalidAuthenticityToken exception on token mismatch
Turbo/Rails UJS auto-adds X-CSRF-Token header to AJAX requests
Pros
- ✓ Auto-applied โ no developer attention needed
- ✓ form_with auto-inserts tokens
- ✓ OWASP recommended defense technique
- ✓ Auto-compatible with Turbo
Cons
- ✗ Need to disable or adjust for API apps
- ✗ May conflict with CORS configuration
- ✗ Token mismatch error on session expiry
- ✗ Possible issues with multiple tabs