Sub topic 14
Sanitization and Safe Binding Practices
This chapter assumes you know the interpolation and property binding forms from earlier chapters, and that you know what cross-site scripting (XSS) is. XSS happens when an attacker gets their own script to run in another user's page.
Angular Treats Every Bound Value as Untrusted
Angular assumes that any value reaching a binding could come from an attacker. It does not try to tell trusted data from user input. Instead, it looks at where the value is going in the DOM, which it calls the security context, and cleans the value for that context.
Interpolation is the safest form. {{ value }} is written as text content, so a string like <script> shows up as literal characters and is never parsed as HTML. Property bindings to sensitive properties go through the sanitizer:
| Security context | Example bindings | What Angular does |
|---|---|---|
| HTML | `[innerHTML]` | Removes `<script>`, event handler attributes such as `onerror`, and other dangerous markup |
| URL | `[href]`, `[src]` on `img` and `a` | Prefixes dangerous schemes such as `javascript:` with `unsafe:` |
| Resource URL | `[src]` on `iframe` and `script` | Cannot be sanitized, so Angular throws an error unless the value is marked trusted |
| Style | `[style]`, `[style.prop]` | Passed through, because modern browsers do not run code from CSS |
Seeing the Sanitizer at Work
The component below binds a malicious string in several contexts. It also shows the right way to trust an embed URL: check the input against a strict pattern first, then mark it as trusted.
import { Component, inject } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
@Component({
selector: 'app-comment',
template: `
<p>{{ comment }}</p>
<div [innerHTML]="comment"></div>
<a [href]="link">Profile</a>
@if (videoUrl) {
<iframe [src]="videoUrl" width="320" height="180"></iframe>
}
`,
})
export class CommentComponent {
private sanitizer = inject(DomSanitizer);
comment = '<b>Hi</b><img src="x" onerror="alert(1)">';
link = 'javascript:alert(1)';
videoUrl: SafeResourceUrl | null = null;
constructor() {
this.setVideo('dQw4w9WgXcQ');
}
setVideo(id: string) {
if (/^[A-Za-z0-9_-]{11}$/.test(id)) {
this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(
`https://www.youtube.com/embed/${id}`
);
}
}
}The rendered page behaves like this:
- The
<p>shows the raw markup as visible text. - The
<div>renders a bold "Hi" and an image with noonerrorattribute. In development mode the console logs a warning that sanitizing stripped some content. - The link's
hrefbecomesunsafe:javascript:alert(1), so clicking it does nothing. - The iframe loads, because only the video ID came from outside and it was checked before it was trusted.
Patterns That Skip Angular's Protection
The sanitizer only covers template bindings. These common mistakes go around it:
- Writing to the DOM directly.
elementRef.nativeElement.innerHTML = userTextnever reaches the sanitizer. Use a template binding, orRenderer2with values you control. - Building templates from user input. Angular compiles templates ahead of time from your source code. Never concatenate user data into template strings or compile templates at runtime.
- Trusting too broadly. A shared
safeHtmlpipe that callsbypassSecurityTrustHtmlon any input switches sanitization off everywhere the pipe is used. - Relying on the client alone. Sanitization protects the rendered page. Your server still has to validate and encode the data it stores and returns.
Exercise
A user profile has a website field. The template uses <a [href]="user.website">Site</a>, and an attacker sets the field to javascript:stealCookies(). What happens when someone clicks the link, and would calling bypassSecurityTrustUrl(user.website) be a good fix for a warning in the console?
Show answer
Angular sanitizes the value in the URL context and turns it into unsafe:javascript:stealCookies(), so the click runs no script. Calling bypassSecurityTrustUrl would remove that protection and let the attack through. The right fix is to check that the value starts with https:// or http:// before saving or binding it, and leave sanitization on.
Exercise
Why does [innerHTML]="html" strip a script tag, while <iframe [src]="url"> with a plain string throws an error instead of being cleaned?
Show answer
HTML can be cleaned by removing dangerous elements and attributes and keeping the rest. A resource URL loads and runs a whole document or script, and no partial cleanup can make an untrusted one safe. So Angular refuses it unless you explicitly mark it trusted with bypassSecurityTrustResourceUrl.