FlawOpen

flawopen.com/XSS in JavaScript/Angular

Angular XSS protection: safe defaults and risky escape hatches

Reference page
Short answer

Angular treats values in template bindings as untrusted: interpolation escapes text, and HTML and URL bindings use context-aware sanitization. The dangerous boundary is explicit trust: bypassSecurityTrust* tells Angular to skip its normal sanitizer for that value. Use it only after validating and constructing a value in the exact security context where it will be used.

RISKY — the escape hatch
this.safeHtml = this.sanitizer
  .bypassSecurityTrustHtml(comment);
// <div [innerHTML]="safeHtml"></div>
SAFER — keep untrusted input as text
<div>{{ comment }}</div>
// interpolation escapes markup as text

What Angular sanitizes — and what it cannot

Angular escapes interpolated text and sanitizes untrusted values in HTML and URL contexts. For example, [innerHTML] removes unsafe markup while retaining safe HTML; ordinary interpolation does not parse markup at all. A resource URL (such as an iframe source that loads executable content) cannot be generically sanitized because it may identify arbitrary code. Never pass attacker-controlled values to bypassSecurityTrustHtml, bypassSecurityTrustUrl, bypassSecurityTrustResourceUrl, or the related bypass APIs: they assert that the value is safe for a specific context and skip sanitization. For a legitimate embed, construct the URL from a fixed origin and validated identifier immediately before marking it trusted.

Audit escape hatches and DOM sinks

grep -rn "bypassSecurityTrust" --include="*.ts" .

FAQ

Defense in depth with CSP and Trusted Types

Use Content Security Policy (CSP) and enforce Trusted Types as defense in depth alongside safe Angular bindings. Angular requires the angular#unsafe-bypass Trusted Types policy when an application calls DomSanitizer.bypassSecurityTrust*. Prefer removing those calls; if one is necessary, inventory each call site and trust only a value validated for its exact context.

Does Angular sanitize every way of writing to the DOM?

No. Angular template bindings receive framework protections, but direct DOM APIs, ElementRef, and third-party DOM libraries can bypass them. Prefer template bindings, audit those sinks separately, and do not mark input trusted unless code has validated it for the exact security context.

References

See also Cross-Site Scripting (XSS, CWE-79): How It Works and How to Prevent It in Every Language — flawopen.com Content-Type Sniffing XSS: MIME Types and nosniff CSP vs. Output Escaping: Do You Need Both? Is React's dangerouslySetInnerHTML Safe? Is DOMPurify Enough for Safe innerHTML? Is Markdown Rendering Safe from XSS? Is Svelte Safe from XSS by Default?