Chapter 12.5☕ 15 min read

Security — XSS, CSRF, Sanitization

Frontend apps public hain — hackers hamesha ready. Seekho kaise bachna hai.

01Kyuu?

Frontend apps are public — anyone can see and modify your code. Common attacks include XSS (Cross-Site Scripting), CSRF (Cross-Site Request Forgery), and injection attacks.

"Security = ghar ki lock — chhota attention bada bachaav"

Angular has built-in protection, but you must know the gaps.

02XSS Kya Hai?

XSS (Cross-Site Scripting) happens when an attacker injects malicious script into your page.

Angular AUTO-ESCAPES HTML in templates: {{ userInput }} renders as text, NOT HTML. It escapes <, >, ", & automatically.

"XSS = chhupa hua bomb — Angular {{ }} is safe."

03XSS Kab Hota Hai?

XSS CAN happen when you bypass Angular escaping:

[innerHTML]="userInput"DANGEROUS! Renders raw HTML.

  • <img onerror="steal()" src="x"> — event handlers execute!
  • <svg onload="attack()"> — SVG event handlers work
04DomSanitizer

If you must use [innerHTML]:

private sanitizer = inject(DomSanitizer);
safeHtml = this.sanitizer.bypassSecurityTrustHtml(cleanedHtml);

Better: use DOMPurify to clean HTML first:

import DOMPurify from 'dompurify';
cleanHtml = DOMPurify.sanitize(userInput);

Double protection: DOMPurify clean, DomSanitizer allow.

05CSRF

CSRF (Cross-Site Request Forgery) — fake requests from malicious sites using your session.

Angular HttpClient automatically handles CSRF: reads XSRF-TOKEN cookie from backend, sends as X-XSRF-TOKEN header.

"CSRF = fake order — Angular handles it automatically!"

Security Takeaways

  • {{ }} auto-escapes — safe by default
  • [innerHTML] bypasses escape — sanitize with DOMPurify!
  • DomSanitizer.bypassSecurityTrustHtml() — last resort after cleaning
  • CSRF handled automatically by HttpClient
  • Never disable CSRF unless using token auth only
Course Search
Search across all chapters & stages
📖

Search the course

Type any topic — branching, stash, rebase, hooks — and jump straight to that chapter.

merge branchesgit stashundo commitrebase