๐Ÿ›ก๏ธ

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_session

  • AJAX requests send token via X-CSRF-Token header

  • Turbo automatically includes CSRF token

Key Points

1

protect_from_forgery auto-configured in ApplicationController (Rails default)

2

csrf_meta_tags inserts token in <head>

3

form_with auto-adds hidden authenticity_token field

4

Server validates tokens for POST/PATCH/DELETE requests

5

ActionController::InvalidAuthenticityToken exception on token mismatch

6

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

Use Cases

All Rails web applications Form submission protection AJAX request protection Separate API and web authentication