What is the difference between Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF), and how do you prevent each?
Quick Revision Summary
XSS injects untrusted scripts to execute in victim browsers; CSRF tricks authenticated browsers into making unwanted requests. Prevent XSS via escaping/CSP; prevent CSRF via tokens and SameSite cookies.
Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Saved automatically
Model Answer & Deep-Dive Explanation
Cross-Site Scripting (XSS):
- Vulnerability: An attacker injects malicious client-side JavaScript into a web application, which executes in other users' browsers.
- Impact: Session token theft, keystroke logging, DOM defacement.
- Mitigation: Context-aware HTML entity encoding, using frameworks that auto-escape input (e.g. React, EJS
<%= %>), implementing strictContent-Security-Policy (CSP)headers, and settingHttpOnlycookies.
Cross-Site Request Forgery (CSRF):
- Vulnerability: A malicious site tricks an authenticated user's browser into transmitting unauthorized state-changing requests (e.g. transferring money) to a target website that trusts the user's cookies.
- Mitigation: Anti-CSRF Synchronizer Tokens (validated on POST/PUT/DELETE requests), and configuring
SameSite=StrictorSameSite=Laxcookie attributes.
Interviewer Evaluation Points & Scoring Rubric
- 1 1. Distinguishes code injection (XSS) from unauthorized action forgery (CSRF). 2. Mentions SameSite and Anti-CSRF tokens. 3. Recommends CSP and HttpOnly cookies.
Related Questions in Full Stack Web Development
Compare Microservices Architecture with Monolithic Architecture: Trade-offs, Scalability, and Distributed Challenges.
Advanced level • 94 views
How should client-side and server-side form validation work together?
Easy level • 68 views
What is Idempotency in REST APIs, and how should HTTP methods and status codes be structured?
Intermediate level • 65 views
A page makes one database query per displayed item. What is the problem and how would you fix it?
Medium level • 60 views
Compare REST APIs with GraphQL: Architectural differences, advantages, trade-offs, and when to use which.
Intermediate level • 58 views