angular如何防止xss攻击

作者:袖梨 2026-08-22

img_6a88e98193ea130.webp

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攻击,例如:

// htmlAn untrusted URL:Click meA trusted URL:Click me// jsimport { DomSanitizer } from '@angular/platform-browser';@Component({...})export class DemoComponent {constructor(private sanitizer: DomSanitizer) {}this.dangerousUrl = 'javascript:alert("Hi there")';// 人为信任该urlthis.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);}

相关文章

精彩推荐