Skip to content

Instantly share code, notes, and snippets.

@MurhafSousli
Last active August 16, 2023 04:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MurhafSousli/3d2ddb777c8ce88e2400bd93f694cd3b to your computer and use it in GitHub Desktop.
Save MurhafSousli/3d2ddb777c8ce88e2400bd93f694cd3b to your computer and use it in GitHub Desktop.
HTML Dom Sanitizer Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'sanitizeHtml'
})
export class HtmlSanitizerPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
transform(value: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
@juliandavidmr
Copy link

You can add types:

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

...

transform(html: string) : SafeHtml {
  return this._sanitizer.bypassSecurityTrustHtml(html);
}

@yawnston
Copy link

yawnston commented Sep 9, 2020

To anyone reading this - this pipe DOES NOT SANITIZE THE HTML! If the passed HTML contains script tags inserted by an attacker, you just got your site successfully attacked by XSS! What this pipe does is it tells Angular to trust the given value as safe, e.g. to not escape any <script> tags contained inside it for example. Only use this pipe when you are 100% sure that the input is safe! The DomSanitizer contains a sanitize function which can sanitize potentially dangerous HTML for you.

The documentation for the bypassSecurityTrustHtml function has this to say: **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks!.

@gabriel-messas
Copy link

To anyone reading this - this pipe DOES NOT SANITIZE THE HTML! If the passed HTML contains script tags inserted by an attacker, you just got your site successfully attacked by XSS! What this pipe does is it tells Angular to trust the given value as safe, e.g. to not escape any <script> tags contained inside it for example. Only use this pipe when you are 100% sure that the input is safe! The DomSanitizer contains a sanitize function which can sanitize potentially dangerous HTML for you.

The documentation for the bypassSecurityTrustHtml function has this to say: **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks!.

I was crazy here seeing that nobody pointed that out.
This is not a sanitization pipe! It is a bypass!

@MurhafSousli
Copy link
Author

Angular service calls the service that bypass the content DomSanitizer, assuming you know what you're doing! the gist name was just a short name for a pipe that uses the DomSanitizer to bypass html content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment