建站云服务器angular防止xss攻击的示例:
angular提供了一个DomSanitizer服务,提供的方法如下:
export enum SecurityContext { NONE, HTML, STYLE, SCRIPT, URL, RESOURCE_URL }
export abstract class DomSanitizer implements Sanitizer {
// 过滤恶意代码,可设置过滤类型
abstract sanitize(context: SecurityContext, value: SafeValue|string|null): string|null;
// 跳过html的检查
abstract bypassSecurityTrustHtml(value: string): SafeHtml;
// 跳style的检查
abstract bypassSecurityTrustStyle(value: string): SafeStyle;
// 跳过script的检查
abstract bypassSecurityTrustScript(value: string): SafeScript;
// 跳过style的检查
abstract bypassSecurityTrustUrl(value: string): SafeUrl;
// 跳过url的检查
abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl;
}
应该该服务进行防止xss攻击,例如:
// html
An untrusted URL:
Click me
A trusted URL:
Click me
// js
import { DomSanitizer } from ‘@angular/platform-browser’;
@Component({
…
})
export class DemoComponent {
constructor(private sanitizer: DomSanitizer) {
}
this.dangerousUrl = ‘javascript:alert(“Hi there”)’;
// 人为信任该url
this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
}