【问题标题】:How to prevent html injection in Angular 5如何防止 Angular 5 中的 html 注入
【发布时间】:2019-09-14 19:32:45
【问题描述】:

我想阻止用户向文本框输入 html 注入。我研究了一些示例,但它们通常是关于允许 html 标签通过管道并说 angular 会自动清理 html 标签。但在我的示例中,当我在文本框中输入 <script>alert('blabla')</script> 时,它会被接受并像这样注册到 db..

如何预防?

我的模板代码是:

<div fxLayout="row">
          <mat-form-field fxFlex="20">
            <input matInput name="label" [(ngModel)]="product.label" placeholder="Label"
                   required>
          </mat-form-field>
        </div>

我的 ts 文件是:

import { Product } from '../../../';

@Component({
  selector: '....',
  templateUrl: '....',
  styleUrls: ['....']
})
export class ProductEditComponent implements OnInit {

  product: Product = <Product>{};

  constructor(some services etc.) {

  }

  ngOnInit() {

   //some code
  }

再次注意:我要防止进入html脚本注入,不允许通过bypass或者pipe...

【问题讨论】:

  • 我删除了错误的部分

标签: html angular typescript sanitization


【解决方案1】:

您可以为此使用 DomSanitizer

import { DomSanitizer } from "@angular/platform-browser"
import { SecurityContext } from "@angular/core";

constructor(private sanit:DomSanitizer){
  var dom = this.sanitizer.sanitize(SecurityContext.HTML, "<script> alert('HELLO'); </script>");
  console.log(dom);
}

如果它返回null,那么这是html的问题,否则它返回传递的html

【讨论】:

  • 我的 ngModel product.label 等在哪里。它就像你好是硬编码的。 ?并且那里有关于圣徒的语法错误:Domsanitizer is not used
  • 我想防止html脚本进入不允许html。
猜你喜欢
  • 2017-09-05
  • 2019-04-24
  • 2013-06-14
  • 2014-01-18
  • 2020-12-15
  • 2010-10-26
  • 2015-09-07
  • 2021-03-13
  • 1970-01-01
相关资源
最近更新 更多