Q18: What is Cross-Site Request Forgery (CSRF) and how do cookie-based authentication systems defend against it?
CSRF occurs when a malicious website tricks a user's browser into automatically sending authenticated HTTP requests (including auto-attached cookies) to a target application where the user is currently logged in.
CSRF Defenses:
SameSiteCookie Attribute: SettingSameSite=StrictorSameSite=Laxprevents browsers from sending cookies on cross-site subrequests.- Anti-CSRF Tokens (Synchronizer Token Pattern): Server generates a unique cryptographic token stored in the session and requires it in custom request headers (
X-CSRF-Token). - Custom Header Verification: APIs requiring custom headers (e.g.,
Authorization: Bearer <token>) are immune to traditional browser form CSRF because cross-origin JS cannot set custom headers without failing CORS preflight checks.
Key Takeaways
CSRF targets automatically attached browser cookies; it does not impact header-based Bearer tokens.
Use
SameSite=Strictcookies alongside anti-CSRF tokens for cookie-authenticated APIs.