angular自定义管道记录-安全管道

342 阅读1分钟

借鉴资料: angular中文官网

说明

比如,如果要在 <a [href]="someValue"> 的链接中绑定一个 URL,someValue 将会被净化, 以防范攻击者注入 javascript: 之类的 URL,并借此在网站上执行代码。

在特定场景下,可能要禁用净化机制,比如,如果应用程序真的需要生成具有动态值的 javascript: 链接。 用户可以通过使用 bypassSecurityTrust... 方法来构建出一个值,以绕过安全性检查,并在模板中绑定它。

这种场景其实非常罕见,必须特别小心,避免引入跨站脚本攻击(XSS)类的安全风险。

当使用 bypassSecurityTrust... 时,请尽量确保尽早调用该方法,并且让他尽可能接近值的来源,以便能更容易地验证使用它时有没有引入安全风险。

如果该值本身是安全的,则不需要绕过安全性检查,比如那些没有使用可疑协议的 URL 或者不包含危险代码的 HTML 片段。 净化器会确保值的安全性。

使用方法

<span [innerHtml]="data?.columnCnName | safe: 'html'"></span>

代码如下

import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe',
})
export class SafePipe implements PipeTransform {

  constructor(private _sanitizer: DomSanitizer) {

  }
  public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeResourceUrl | SafeUrl {
    switch (type) {
      case 'html': return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style': return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script': return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url': return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl': return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default: throw new Error(`Invalid safe type specified: ${type}`);
    }
  }
}