錯誤百科

傳給 DomSanitizer 的資源 URL 不安全

當以 SecurityContext.RESOURCE_URL 呼叫 DomSanitizer.sanitize(),且傳入的值未被明確標示為受信任時,Angular 會拋出此錯誤,訊息為 unsafe value used in a resource URL context。

資源 URL 的處理方式與一般 URL 不同。Angular 可以淨化普通的 URL,但無法讓任意的資源 URL 變安全,因為像 <iframe src> 或 <link href> 這類資源 URL 屬性會讓瀏覽器擷取並執行外部內容。因此 sanitize() 會拒絕不受信任的值,而不是嘗試淨化它們。

把不受信任的值繫結到範本或宿主繫結中的這類屬性,則會改拋出 NG0904。

除錯方式

找出使用 SecurityContext.RESOURCE_URL 的 sanitize() 呼叫。任何普通字串都會拋出此錯誤,即使是看起來像靜態的 URL:

@Component({
  selector: 'app-root',
  template: `<iframe [src]="url"></iframe>`,
})
export class App {
  private readonly sanitizer = inject(DomSanitizer);
  url = this.sanitizer.sanitize(SecurityContext.RESOURCE_URL, 'https://example.com/embed'); // throws NG05201
}

如果該 URL 來自受信任且受控制的來源,請使用 DomSanitizer.bypassSecurityTrustResourceUrl 把它標示為安全,並直接繫結結果:

import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
import {Component, inject} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<iframe [src]="safeUrl"></iframe>`,
})
export class App {
  safeUrl: SafeResourceUrl = inject(DomSanitizer).bypassSecurityTrustResourceUrl(
    'https://example.com/embed',
  );
}

CRITICAL: bypassSecurityTrustResourceUrl 是逃生口,不是淨化器。絕不要把使用者提供的 URL 傳給它,那會讓攻擊者載入任意內容,包括惡意指令碼。只有在該值完全由你控制時才使用它。

更多資訊請見安全性指南。