Prevent CSRF (Cross-Site Petición Forgery) attacks
CSRF tricks authenticated usuarios en submitting unwanted requests. Aprender anti-CSRF tokens, SameSite cookies, y double-submit patrones.
- 1
CSRF exploits the browser's automatic sending of cookies. If a user is logged in (cookies present) and visits a malicious site, that site can submit a form to the target site — the cookies are sent automatically. Prevention: (1) Anti-CSRF tokens (synchronizer pattern) — a random token in the form and session, verified on submission. (2) SameSite cookies — cookies are not sent cross-site. (3) Origin/Referer header validation. (4) Require custom headers for state-changing requests.
- 2 Generador de HMAC →
Generar an anti-CSRF token. The token should be: unpredictable (CSPRNG), per-session (or per-request for higher security), and bound to the user's session. HMAC(session_id, random) is a common pattern — it is deterministic (same session → same token) but unforgeable without the secret.
- 3 Calculadora de hash →
For the double-submit pattern: generate a random token, set it as a cookie (not HttpOnly, so JavaScript can read it) and include it as a header in every request. The server verifies that the cookie and header match. This does not require server-side state. Use SHA-256 for the token hash.
Preguntas frecuentes
- Are SameSite cookies enough to prevent CSRF?
- SameSite=Lax (default in modern browsers) prevents CSRF for top-level navigations (form POST, link clicks) but allows GET requests. SameSite=Strict prevents all cross-site sending but breaks legitimate cross-site usage (e.g., following a link to your site from email). Use SameSite=Lax + CSRF tokens for defense in depth.
- CSRF vs XSS — what is the difference?
- XSS executes malicious code in the victim's browser (the attacker reads data or performs actions as the user). CSRF tricks the victim's browser into making a request to a site where they are authenticated (the attacker does not read the response). XSS is a code injection; CSRF is a request forgery. XSS can bypass CSRF protections (the script can read the token).