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:
A trusted URL:
// 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);
}