← Back to Angular, page 4

angular-0061 · Easy fresher

How does Angular protect an app against cross-site scripting (XSS), and what is the danger of bypassSecurityTrustHtml?

Angular treats every bound value as untrusted. Interpolation is escaped as text, and values bound to innerHTML, URLs, and styles are sanitized, so script tags and event handler attributes are removed. DomSanitizer.bypassSecurityTrust* turns that protection off for a value, so it must never receive user-controlled data.

Full answer

Cross-site scripting (XSS) happens when an attacker's text is run as code in another user's browser. For example, a comment field containing <img src=x onerror="stealCookies()"> is dangerous if the page inserts it as HTML.

How Angular defends:

  • Interpolation {{ comment }} and normal property bindings treat the value as text, not as HTML. A <script> string is shown literally.
  • [innerHTML]="comment" is allowed, but Angular sanitizes the value first: it keeps harmless markup (<b>, <p>) and removes scripts, event handler attributes, and unsafe URLs. In development mode, the console warns "sanitizing HTML stripped some content".
  • URL bindings such as [href] and [src] reject unsafe schemes such as javascript:. Style bindings and resource URLs (iframes, scripts) are restricted as well.
  • Templates are compiled ahead of time, so templates are not built from strings at runtime. This removes template injection.

Where apps become vulnerable:

  • DomSanitizer.bypassSecurityTrustHtml(value) (and ...Url, ...ResourceUrl, ...Style, ...Script). These tell Angular that you have checked the value yourself. If the value includes user input, you have created an XSS hole. A custom safeHtml pipe that always calls bypass is a common mistake.
  • Direct DOM access: nativeElement.innerHTML = text or document.write, which skip the sanitizer.
  • Server-built HTML or third-party widgets that insert markup.
  • Libraries with their own template compilers.

Defence in depth: send a strict Content Security Policy header, keep dependencies updated, sanitize on the server too, and store tokens carefully (see the security questions on CSRF). Never rely only on client code for security.

typescript
import { Component, computed, inject, signal } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-comment',
  template: `
    <!-- Escaped text: the script string is shown literally. -->
    <p>{{ comment() }}</p>

    <!-- Sanitized HTML: <b> stays, onerror and script are removed. -->
    <div [innerHTML]="comment()"></div>

    @if (videoUrl(); as url) {
      <iframe [src]="url" title="Lesson video" width="320" height="180"></iframe>
    }
  `,
})
export class CommentComponent {
  private readonly sanitizer = inject(DomSanitizer);

  readonly comment = signal('<b>Nice lesson</b><img src="x" onerror="alert(1)">');
  readonly videoId = signal('dQw4w9WgXcQ');

  // Only an id that matches a strict pattern is used. The host is fixed in code.
  readonly videoUrl = computed<SafeResourceUrl | null>(() => {
    const id = this.videoId();
    if (!/^[\w-]{11}$/.test(id)) {
      return null;
    }
    return this.sanitizer.bypassSecurityTrustResourceUrl(`https://www.youtube.com/embed/${id}`);
  });
}

Angular 20.3, strict template check passes. The video example builds the URL from a validated video id, not from the whole user text.

Key points

  • Interpolation escapes text. `[innerHTML]` is sanitized. Unsafe URL schemes are blocked.
  • `bypassSecurityTrust*` disables protection. Use it only on values you fully control.
  • Direct DOM writes skip the sanitizer.
  • Add a Content Security Policy and server-side checks. Angular alone is not the whole defence.

Common mistakes

  • Creating a pipe that bypasses sanitization for any HTML string.
  • Using `bypassSecurityTrustResourceUrl` with a URL built from user input for an iframe.
  • Assuming Angular makes the server side safe too. It only protects the client template layer.

Follow-ups

  • How would you safely show a YouTube video chosen by a user?
  • What does a Content Security Policy do for XSS?
  • What does the sanitizer remove from `<img src=x onerror=...>`?

Tips

  • Show the bypass danger with a concrete example. Interviewers look for it.
  • Mention defence in depth with CSP.
  • For the YouTube case, say you accept only an allow-listed host and build the URL yourself.

Evaluation rubric

  • Explains default escaping and sanitization.
  • Identifies the bypass methods and direct DOM access as risks.
  • Mentions CSP and server-side checks.