Robbie Mills
Robbie Mills

Reputation: 2945

Bypass Angular unsafe URL's

I have a CMS written in Angular 5 where members can add text including links. The problem is that when the content is rendered with:

<div [innerHTML]="model.content"></div>

Then the links are rendered as

unsafe:\"http://www.example.com\"

and I get this warning:

WARNING: sanitizing unsafe URL value \"https://www.example.com/\" (see http://g.co/ng/security#xss)

How do I disable this? I have seen similar questions that require each URL to be specifically made safe, but I don't know what url's are going to be input.

As it's a very small user base and partitioned via membership then I don't want to have this extra level of security.

Upvotes: 0

Views: 4843

Answers (2)

Armen Vardanyan
Armen Vardanyan

Reputation: 3315

You can create a pipe to reuse it anywhere in your html:

@Pipe({name: 'trust'})
export class TrustPipe implements PipeTransform {
   constructor(private sanitizer: DomSanitizer) {}
   transform(value) {
     return this.sanitizer.bypassSecurityTrustHtml(value);
   }
}

And then use it in your html:

<div [innerHTML]="model.content | trust"></div>

Upvotes: 4

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

You should inject DomSanitizer to your component and byPassSecurity control.

@Component({
   selector: 'my-comp',
   template: `
       <div [innerHTML]="url"></div>
   `
})
export class MyComponent {

   url;
   content;
   constructor(private sanitizer: DomSanitizer) {}

   ngOnInit() {
       this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.content);
   }

}

For more info, check the docs

Upvotes: 1

Related Questions