W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
有時候,應(yīng)用程序確實需要包含可執(zhí)行的代碼,比如使用 URL
顯示 <iframe>
,或者構(gòu)造出有潛在危險的 URL。 為了防止在這種情況下被自動無害化,你可以告訴 Angular:我已經(jīng)審查了這個值,檢查了它是怎么生成的,并確信它總是安全的。 但是千萬要小心!如果你信任了一個可能是惡意的值,就會在應(yīng)用中引入一個安全漏洞。如果你有疑問,請找一個安全專家復(fù)查下。
注入 DomSanitizer 服務(wù),然后調(diào)用下面的方法之一,你就可以把一個值標(biāo)記為可信任的。
bypassSecurityTrustHtml
bypassSecurityTrustScript
bypassSecurityTrustStyle
bypassSecurityTrustUrl
bypassSecurityTrustResourceUrl
記住,一個值是否安全取決于它所在的環(huán)境,所以你要為這個值按預(yù)定的用法選擇正確的環(huán)境。假設(shè)下面的模板需要把 javascript.alert(...)
方法綁定到 URL
。
Path:"src/app/bypass-security.component.html (URL)" 。
<h4>An untrusted URL:</h4>
<p><a class="e2e-dangerous-url" [href]="dangerousUrl">Click me</a></p>
<h4>A trusted URL:</h4>
<p><a class="e2e-trusted-url" [href]="trustedUrl">Click me</a></p>
通常,Angular 會自動無害化這個 URL 并禁止危險的代碼。為了防止這種行為,可以調(diào)用 bypassSecurityTrustUrl
把這個 URL 值標(biāo)記為一個可信任的 URL
:
Path:"src/app/bypass-security.component.ts (trust-url)" 。
constructor(private sanitizer: DomSanitizer) {
// javascript: URLs are dangerous if attacker controlled.
// Angular sanitizes them in data binding, but you can
// explicitly tell Angular to trust this value:
this.dangerousUrl = 'javascript:alert("Hi there")';
this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
如果需要把用戶輸入轉(zhuǎn)換為一個可信任的值,可以在控制器方法中處理。下面的模板允許用戶輸入一個 YouTube 視頻的 ID, 然后把相應(yīng)的視頻加載到 <iframe>
中。<iframe src>
是一個“資源 URL”的安全環(huán)境,因為不可信的源碼可能作為文件下載到本地,被毫無防備的用戶執(zhí)行。 所以要調(diào)用一個控制器方法來構(gòu)造一個新的、可信任的視頻 URL
,這樣 Angular 就會允許把它綁定到 <iframe src>
。
Path:"src/app/bypass-security.component.html (iframe)" 。
<h4>Resource URL:</h4>
<p>Showing: {{dangerousVideoUrl}}</p>
<p>Trusted:</p>
<iframe class="e2e-iframe-trusted-src" width="640" height="390" [src]="videoUrl"></iframe>
<p>Untrusted:</p>
<iframe class="e2e-iframe-untrusted-src" width="640" height="390" [src]="dangerousVideoUrl"></iframe>
Path:"src/app/bypass-security.component.ts (trust-video-url)" 。
updateVideoUrl(id: string) {
// Appending an ID to a YouTube URL is safe.
// Always make sure to construct SafeValue objects as
// close as possible to the input data so
// that it's easier to check if the value is safe.
this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
this.videoUrl =
this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: