Angular prevents cross-site scripting (XSS) by treating all values as untrusted by default and sanitizing them before they are inserted into the
DOM.
The DomSanitizer service provides bypass methods that allow developers to mark values as trusted, skipping this sanitization.
Calling a DomSanitizer bypass method such as bypassSecurityTrustHtml, bypassSecurityTrustScript,
bypassSecurityTrustUrl, bypassSecurityTrustResourceUrl, or bypassSecurityTrustStyle marks a value as safe for
the corresponding context, preventing Angular from sanitizing it on insertion into the DOM.
If the bypassed value is constructed from or contains user-controlled data, an attacker can inject malicious content into the page.
An attacker who controls the content passed to a DomSanitizer bypass method can inject arbitrary HTML or JavaScript into the page.
This can allow the attacker to steal session tokens or credentials, perform actions on behalf of the victim, access or modify sensitive information,
or redirect users to malicious sites.
Avoid disabling Angular’s built-in sanitization unless absolutely necessary. When using a bypass method is unavoidable, make sure you fully understand how the trusted value is constructed, never concatenate it with user-controlled data, and choose the correct bypass method for the context.
import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
import { ActivatedRoute } from '@angular/router';
@Component({
template: '<div id="hello" [innerHTML]="hello"></div>'
})
export class HelloComponent implements OnInit {
hello: SafeHtml;
constructor(private sanitizer: DomSanitizer, private route: ActivatedRoute) { }
ngOnInit(): void {
let name = this.route.snapshot.queryParams.name;
let html = "<h1>Hello " + name + "</h1>";
this.hello = this.sanitizer.bypassSecurityTrustHtml(html); // Noncompliant
}
}
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";
import { ActivatedRoute } from '@angular/router';
@Component({
template: '<div id="hello"><h1>Hello {{name}}</h1></div>',
})
export class HelloComponent implements OnInit {
name: string;
constructor(private sanitizer: DomSanitizer, private route: ActivatedRoute) { }
ngOnInit(): void {
this.name = this.route.snapshot.queryParams.name;
}
}