6

我浏览了这两个功能的角度文档

bypassSecurityTrustUrl

绕过安全性并相信给定的值是一个安全样式的 URL,即可以在超链接或<img src>

bypassSecurityTrustResourceUrl其中说

绕过安全性并相信给定的值是一个安全的资源 URL,即一个可用于加载可执行代码的位置,如<script src><iframe src>

以上两者都用于绕过安全和信任。

我绕过了blob url <img src>,所以在浏览文档之前,我的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'

它实际上正在工作!!!!

所以我的问题是这两个功能有什么区别。如果可以使用其中任何一个,为什么要使用两个不同的功能?

4

2 回答 2

3

我实际上正在为SafeValues 创建管道并且对此感兴趣。所以我开始挖掘,这就是我发现的:

DomSanitizationService: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)`);
  }

现在我们知道ResourceUrl在任何地方Url都允许这样做。

于 2019-09-20T13:16:30.540 回答
0

我发现在清理图像或视频时需要使用 bypassSecurityTrustResourceUrl,而在清理包含 pdf、word 或 excel 等应用程序内容的文件时需要使用 bypassSecurityTrustUrl。

于 2020-03-31T05:41:33.507 回答