# XSS Prevention in Angular Complete guide to preventing Cross-Site Scripting (XSS) attacks in Angular applications. ## Table of Contents 1. [Understanding XSS](#understanding-xss) 2. [Angular's Built-in Protection](#angulars-built-in-protection) 3. [DomSanitizer](#domsanitizer) 4. [Content Security Policy](#content-security-policy) 5. [Secure Coding Patterns](#secure-coding-patterns) 6. [Common Vulnerabilities](#common-vulnerabilities) 7. [Testing for XSS](#testing-for-xss) --- ## Understanding XSS ### Types of XSS **1. Stored XSS (Persistent)** ```typescript // Attacker stores malicious script in database userBio = ''; // Later displayed to other users
// Executes script ``` **2. Reflected XSS (Non-persistent)** ```typescript // Malicious link: https://example.com?search= // App reflects input without sanitization
Search results for: {{ searchQuery }}
``` **3. DOM-based XSS** ```typescript // URL: https://example.com# // Unsafe DOM manipulation element.innerHTML = location.hash.substring(1); ``` ### XSS Attack Vectors ```typescript // Script tags // Event handlers
// Data URLs // JavaScript URLs // Style injection
// SVG // Object/embed ``` --- ## Angular's Built-in Protection ### Automatic Escaping ```typescript // ✅ SAFE: Angular auto-escapes @Component({ template: `
{{ userInput }}
` }) export class SafeComponent { userInput = ''; // Rendered as text, not executed } ``` ### Security Contexts Angular sanitizes based on context: | Context | Element | Sanitization | |---------|---------|--------------| | HTML | `[innerHTML]` | Remove scripts, styles | | Style | `[style]` | Remove dangerous CSS | | URL | `[href]`, `[src]` | Block javascript: | | Resource URL | ` // ✅ SECURE: Whitelist domains @Component({ template: `` }) export class VideoComponent { @Input() set videoUrl(url: string) { const trusted = ['youtube.com', 'vimeo.com']; try { const domain = new URL(url).hostname; if (trusted.some(t => domain.includes(t))) { this.trustedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url); } else { console.warn('Untrusted video domain:', domain); this.trustedUrl = null; } } catch { this.trustedUrl = null; } } trustedUrl: SafeResourceUrl | null; constructor(private sanitizer: DomSanitizer) {} } ``` --- ## Testing for XSS ### Manual Testing ```typescript // Test payloads const xssPayloads = [ '', '', '', 'javascript:alert("XSS")', '', '', '