CSRF Cross-Site Request Forgery and Defense
Explain CSRF attacks and how to defend against them.
How It Works
An attacker tricks a logged-in user into visiting a malicious page that automatically sends requests to the target site, using the user's cookies to perform unauthorized actions.
Defense Strategies
1. CSRF Token
The server embeds a random token in forms and validates it on submission. Attackers cannot obtain the correct token.
2. SameSite Cookie Attribute
Set SameSite=Strict or SameSite=Lax so browsers only send cookies on same-site requests.
3. Validate Origin/Referer Header
The server checks whether the request Origin matches an allowed domain.
4. Custom Request Headers
Require a custom header (e.g., X-Requested-With) that cross-site requests cannot set.
Relationship with CORS
Proper CORS configuration does not prevent CSRF; combine with the above measures.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
