Verified Jobs Live
Full Stack Web Development Intermediate Level ~4 min read

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.
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 strict Content-Security-Policy (CSP) headers, and setting HttpOnly cookies.

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=Strict or SameSite=Lax cookie 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.