Angular,DomSanitizer,bypassSecurity脚本

时间:2018-04-19 14:09:31

标签: javascript html angular angular-dom-sanitizer

我正在玩Angular的bypassSecurityTrust*个功能。目标是在页面上执行script标记。但它要么继续使用消息进行消毒

WARNING: sanitizing HTML stripped some content

或者我在控制台中看到了

SafeHtmlImpl {changingThisBreaksApplicationSecurity: "<script>alert(1)</script>

目标是让这个工作。

我目前使用和尝试的内容:

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value: string): string {
    console.log(this.sanitized.sanitize(SecurityContext.NONE, value))
    return this.sanitized.sanitize(SecurityContext.NONE, value);
  }
}
@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit {

  name: string;
  html: string;
  constructor(private sanitizer: DomSanitizer) {
    this.name = 'Angular2';
    this.html = "<script> alert(8) </script>";
  }
  ngOnInit() {
  }
}

和模板html:

<div [innerHtml]="html | safeHtml"></div>

我尝试使用sanitize SecurityContext.NONE同时查看codebypassSecurityTrustHtml(value)。上面的代码受到answer的启发。

关于如何执行JavaScript的任何想法?

1 个答案:

答案 0 :(得分:0)

所以是的,innerHtml不能插入脚本标签,但它并没有从许多其他注入JavaScript的方式中阻止它。

工作示例:

import { Component, Pipe, PipeTransform, SecurityContext} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser'

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

@Component({
  selector: 'app-demo',
  template: `
    <div [innerHtml]="html | safeHtml">
    </div>
  `
})

export class DemoComponent {

  html: string;
  h_html: string;
  constructor(private sanitizer: DomSanitizer) {
    this.html = "<svg onload=\"alert(1)\"> blah </svg>"
    this.h_html = sanitizer.sanitize(SecurityContext.HTML, "<svg onload=\"alert(2)\"> blah </svg>');
  }
}

什么不起作用

return this.sanitized.sanitize(SecurityContext.HTML, value);

或使用

<div [innerHtml]="h_tmpl"></div>

不确定原因。应该表现得一样。