1 year ago

#384616

test-img

Bryan

HTML Sanitizing in Angular isn't removing links

I am storing data entered by users via a rich text editor and displaying that data in my template using innerHtml. If a user hypothetically enters some sort of HTML into the rich text editor, then that HTML ends up being rendered in the template, which is obviously a security risk. To prevent this, I have tried sanitizing the html with the following:

Custom Pipe:

@Pipe({ name: 'safeHtml' })
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitized: DomSanitizer) {}
  transform(value: string) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

HTML:

<span [innerHtml]="userData | safeHtml"></span>

The above code for some reason isn't working, so I tried to sanitize the data in my class instead, like so:

import { DomSanitizer } from '@angular/platform-browser';
...
constructor(private sanitizer: DomSanitizer) {}
...
const userData = this.sanitizer.sanitize(SecurityContext.HTML, response.userData);

This approach successfully stripped out input elements, but it still renders anchor tags as clickable links. Shouldn't the link be stripped out too? How do I strip out all potentially unsafe HTML (forms, inputs, scripts, links, etc.)? I tried passing SecurityContext.URL as the first argument in the sanitize function, but all that did was prepend the string unsafe: to the HTML that was rendered. It didn't remove or disable the link.

Here is documentation for what arguments to pass to the sanitize function: https://angular.io/api/core/SecurityContext

angular

sanitization

0 Answers

Your Answer

Accepted video resources