Security Basics (XSS, CSRF)

Web security is essential for protecting users and data. Two common vulnerabilities are Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). Understanding their nature and mitigation techniques is crucial for safe JavaScript development.

Illustration of Security Basics (XSS, CSRF)
Illustration of Security Basics (XSS, CSRF)

💡 What is XSS?

XSS attacks occur when an attacker injects malicious scripts into trusted websites, which then execute in other users' browsers, potentially stealing data or hijacking sessions.

💡 What is CSRF?

CSRF tricks a logged-in user’s browser into sending unauthorized requests to a web application, exploiting the user’s authenticated state without their consent.

XSS vs CSRF: Core Differences
AspectXSSCSRF
TargetEnd users' browsersAuthenticated users performing actions
Attack VectorMalicious scripts injected into webpagesUnauthorized requests forged from user’s browser
GoalSteal data, hijack session, deface sitePerform unwanted actions on behalf of user
Common DefenseInput sanitization, Content Security PolicyCSRF tokens, SameSite cookies

How XSS Happens

When user input is displayed on a webpage without proper escaping or sanitization, an attacker can insert HTML or JavaScript code that runs in other users’ browsers.

📌 Deep Dive: Unsafe HTML Injection Example

JAVASCRIPT
const userInput = '<script>alert("XSS")</script>';
document.getElementById('output').innerHTML = userInput;
Output
Alert box pops up executing injected script

Mitigation: Always sanitize or escape user input before inserting it into the DOM. Use safe methods like textContent instead of innerHTML when possible.

How CSRF Works

If a user is logged into a site, their browser sends authentication cookies automatically. An attacker can trick the browser into sending a forged request, for example via a hidden form or image tag on another site.

📌 Deep Dive: CSRF Attack Concept

HTML
<img src="https://bank.com/transfer?amount=1000&to=attacker" style="display:none" />
Output
Browser sends GET request to bank.com, transferring money unknowingly

Mitigation: Use anti-CSRF tokens that must be submitted with state-changing requests, and enable SameSite cookie attribute to restrict cross-origin requests.

⚠️ Key Security Practices

  • Never trust user input — always sanitize and validate.
  • Use Content Security Policies (CSP) to limit script execution.
  • Implement CSRF tokens for all sensitive POST/PUT/DELETE requests.
  • Set cookies with HttpOnly and SameSite=Strict or Lax.
  • Keep libraries and frameworks up to date to patch known vulnerabilities.

💡 Remember

XSS exploits flaws in output handling; CSRF exploits authenticated state and trust. Defenses differ but both require secure coding and server-side protections.