样式
<div [style.background-image]="\'url(\' + image + \')\'">Background</div>
<div [style.transform]="rotate(7deg)"
不再添加
答案 0 :(得分:102)
更新(2.0.0 final)
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'safeHtml'})
export class SafeHtml implements PipeTransform {
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustStyle(html);
// return this.sanitizer.bypassSecurityTrustHtml(html);
// return this.sanitizer.bypassSecurityTrustScript(html);
// return this.sanitizer.bypassSecurityTrustUrl(html);
// return this.sanitizer.bypassSecurityTrustResourceUrl(html);
}
}
另见https://angular.io/api/platform-browser/DomSanitizer
<div [innerHTML]="someHtml | safeHtml"
<强>更新强>
DomSanitizationService
将在RC.6中重命名为DomSanitizer
<强>原始强>
这应该在RC.2中修复
另见Angular2 Developer Guide - Security
Angular2在RC.1中引入了CSS值和属性绑定的清理,如[innerHTML]=...
和[src]="..."
另见https://github.com/angular/angular/issues/8491#issuecomment-217467582
使用DomSanitizer.bypassSecurityTrustStyle(...)
import {DomSanitizer} from '@angular/platform-browser';
...
constructor(sanitizer: DomSanitizationService) {
this.backgroundImageStyle = sanitizer.bypassSecurityTrustStyle('url(' + this.image + ')');
// for HTML
// this.backgroundImageStyle = sanitizer.bypassSecurityTrustHtml(...);
}
并绑定到此值而不是不受信任的普通字符串。
这也可以包装在像
这样的管道中@Pipe({name: 'safeStyle'})
export class Safe {
constructor(private sanitizer:Sanitizer){}
transform(style) {
return this.sanitizer.bypassSecurityTrustStyle(style);
// return this.sanitizer.bypassSecurityTrustHtml(style);
// return this.sanitizer.bypassSecurityTrustScript(value);
// return this.sanitizer.bypassSecurityTrustUrl(value);
// return this.sanitizer.bypassSecurityTrustResourceUrl(value);
}
}
<div [ngStyle]="someStyle | safeStyle"></div>
与
someHtml = `<a href="#" onClick="alert(document.cookie);">click to see the awesome</a>`;
仍然有效: - [(正在进行的工作)
Plunker example(Angular 2.0.0-rc-1)
另见Angular 2 Security Tracking Issue
和https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
提示{{...}}
无法使用prop="{{sanitizedContent}}"
绑定已清理的内容,因为{{}}
会在分配之前对其进行字符串化,从而中断清理。
答案 1 :(得分:2)
绕过消毒剂来信任任何内容可能是安全问题。由于Angular不是专门的消毒库,因此对可疑内容过分热衷以不承担任何风险。例如,它删除几乎所有属性。您可以将清理委托给专用的库-DOMPurify。这是我制作的包装器库,可以轻松地将Angular与DOMPurify结合使用。
https://github.com/TinkoffCreditSystems/ng-dompurify
它还有一个管道以声明方式清理HTML:
<div [innerHtml]="value | dompurify"></div>
要记住的一件事是DOMPurify非常适合清理HTML / SVG,而不是CSS。因此,您可以提供Angular的CSS清理程序来处理CSS:
import {NgModule, ɵ_sanitizeStyle} from '@angular/core';
import {SANITIZE_STYLE} from '@tinkoff/ng-dompurify';
@NgModule({
// ...
providers: [
{
provide: SANITIZE_STYLE,
useValue: ɵ_sanitizeStyle,
},
],
// ...
})
export class AppModule {}
它是内部的— ɵ
前缀,但这也是Angular团队在其自己的程序包中始终使用它的方式。