简体   繁体   中英

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.

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM