簡體   English   中英

bypassSecurityTrustResourceUrl 和 bypassSecurityTrustUrl 有什么區別

[英]What is difference between bypassSecurityTrustResourceUrl and bypassSecurityTrustUrl

我瀏覽了兩個函數的角度文檔

bypassSecurityTrustUrl

繞過安全性並將給定的值信任為安全樣式的 URL,即可以在超鏈接或<img src>使用的值

bypassSecurityTrustResourceUrl

繞過安全性並將給定值信任為安全資源 URL,即可用於加載可執行代碼的位置,例如<script src><iframe src>

以上都用於繞過安全和信任。

我繞過了<img src>的 blob url,所以在閱讀文檔之前,我的 IDE (vscode) 展示了上述兩個函數,我使用了bypassSecurityTrustResourceUrl ,我的代碼就像......這樣。

組件.ts

    this.fileService.getFileBlobUrl(imgsrc).subscribe(url => {
      this.domSanitizer.bypassSecurityTrustResourceUrl
      user.bloburl = this.domSanitizer.bypassSecurityTrustResourceUrl(url);
    });

組件.html

    <img [src]="user.bloburl" class="avatar" alt="avatar">

根據文檔bypassSecurityTrustUrl應該可以工作。 但我使用了“bypassSecurityTrustResourceUrl”

它實際上正在工作!!!!

所以我的問題是這兩個功能之間有什么區別。 如果可以使用其中任何一個,為什么會有兩個不同的功能?

我實際上正在為SafeValue創建管道, SafeValue也很感興趣。 所以我開始挖掘,這是我發現的:

DomSanitizationService: sanitization sanitization() :

      case SecurityContext.URL:
        const type = getSanitizationBypassType(value);
        if (allowSanitizationBypassOrThrow(value, BypassType.Url)) {
          return unwrapSafeValue(value);
        }
        return _sanitizeUrl(String(value));
      case SecurityContext.RESOURCE_URL:
        if (allowSanitizationBypassOrThrow(value, BypassType.ResourceUrl)) {
          return unwrapSafeValue(value);
        }

所以這里unwrapSafeValue函數在兩種類型中都被調用,但下面我們有:

DomSanitizationService:

  bypassSecurityTrustUrl(value: string): SafeUrl { 
    return bypassSanitizationTrustUrl(value); 
  }
  bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl {
    return bypassSanitizationTrustResourceUrl(value);
  }

所以這里調用了 2 個不同的函數,讓我們更深入。

sanitization/bypass.ts我們可以找到:

export function bypassSanitizationTrustUrl(trustedUrl: string): SafeUrl {
  return new SafeUrlImpl(trustedUrl);
}
export function bypassSanitizationTrustResourceUrl(trustedResourceUrl: string): SafeResourceUrl {
  return new SafeResourceUrlImpl(trustedResourceUrl);
}

幾行我們可以發現它們之間的唯一區別在於返回的類:

class SafeUrlImpl extends SafeValueImpl implements SafeUrl {
  getTypeName() { return BypassType.Url; }
}
class SafeResourceUrlImpl extends SafeValueImpl implements SafeResourceUrl {
  getTypeName() { return BypassType.ResourceUrl; }
}

因為

if (actualType != null && actualType !== type) {
    // Allow ResourceURLs in URL contexts, they are strictly more trusted.
    if (actualType === BypassType.ResourceUrl && type === BypassType.Url) return true;
    throw new Error(
        `Required a safe ${type}, got a ${actualType} (see http://g.co/ng/security#xss)`);
  }

現在我們知道在Url所在的任何地方都允許使用ResourceUrl

我發現在清理圖像或視頻時需要使用 bypassSecurityTrustResourceUrl,而在清理包含 pdf 或 word 或 excel 等應用程序內容的文件時需要使用 bypassSecurityTrustUrl。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM