bypassSecurityTrustResourceUrl 和 bypassSecurityTrustUrl 有什么区别

san*_*eev 6 angular2-security angular angular8

我浏览了两个函数的角度文档

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);
    });
Run Code Online (Sandbox Code Playgroud)

组件.html

    <img [src]="user.bloburl" class="avatar" alt="avatar">
Run Code Online (Sandbox Code Playgroud)

根据文档bypassSecurityTrustUrl应该可以正常工作。但我使用了“bypassSecurityTrustResourceUrl”

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

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

Dan*_*cal 7

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

DomSanitization服务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);
        }
Run Code Online (Sandbox Code Playgroud)

所以这里的unwrapSafeValue函数在两种类型中都被调用,但下面我们有:

DomSanitization服务:

  bypassSecurityTrustUrl(value: string): SafeUrl { 
    return bypassSanitizationTrustUrl(value); 
  }
  bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl {
    return bypassSanitizationTrustResourceUrl(value);
  }
Run Code Online (Sandbox Code Playgroud)

这里调用了两个不同的函数,让我们更深入地了解一下。

sanitization/bypass.ts中我们可以找到:

export function bypassSanitizationTrustUrl(trustedUrl: string): SafeUrl {
  return new SafeUrlImpl(trustedUrl);
}
export function bypassSanitizationTrustResourceUrl(trustedResourceUrl: string): SafeResourceUrl {
  return new SafeResourceUrlImpl(trustedResourceUrl);
}
Run Code Online (Sandbox Code Playgroud)

通过几行我们可以发现它们之间的唯一区别在于返回的类:

class SafeUrlImpl extends SafeValueImpl implements SafeUrl {
  getTypeName() { return BypassType.Url; }
}
class SafeResourceUrlImpl extends SafeValueImpl implements SafeResourceUrl {
  getTypeName() { return BypassType.ResourceUrl; }
}
Run Code Online (Sandbox Code Playgroud)

并且因为

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)`);
  }
Run Code Online (Sandbox Code Playgroud)

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

  • +1用于挖掘..但我不明白为什么谷歌创建了两个实际上做同样事情的函数...哈哈。 (2认同)