Security — XSS, CSRF, Sanitization
Frontend apps public hain — hackers hamesha ready. Seekho kaise bachna hai.
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.
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."
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
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.
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
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login