【问题标题】:How can I pass HTML as string and bypass Security?如何将 HTML 作为字符串传递并绕过安全性?
【发布时间】:2019-08-05 06:50:54
【问题描述】:

我想使用 ionic-alert-controller 向用户显示消息。此消息是富文本,可能包含链接,警报实际上允许这些链接,并且对于大多数链接来说就像一个魅力。

但是(当链接是指向另一个应用程序的深层链接时)Angular 有时会认为它们不安全,从而使链接无法点击。我怎样才能防止这种行为?警报只接受字符串作为消息,不接受 SafeHTML。

this.a : string = getRichTextFromServer();

// EXAMPLE
// this.a = `<a href="www.google.de">works like a charm</a>
// Hello Hello <b>Example Text</b>
// <a href="sd-viewer://testlink">UNSAFE LINK</a>
// `;

// Some links are marked as unsafe
this.alertCtrl.create({
      message: this.a
    });
    
    
// Doesn't compile as message is only allowed to be a string
this.alertCtrl.create({
      message: this.domSan.bypassSecurityTrustHTML(this.a)
    });
    
// Gives error that function must be used with property binding
this.alertCtrl.create({
      message: this.domSan.bypassSecurityTrustHTML(this.a).toString()
    });
    
// Some links are marked as unsafe again
this.alertCtrl.create({
      this.ds.sanitize(SecurityContext.HTML,
        this.ds.bypassSecurityTrustHtml(a)
      )
    });

我可以在这里做什么?

编辑:HTML(在我的示例中存储在“a”中)是从后端动态加载的,因此在编译时不知道。因此,在运行时对其进行编辑以将 RichText 转换为 Angular 语法似乎很 hacky。

【问题讨论】:

    标签: angular ionic-framework ionic2 ionic3


    【解决方案1】:

    嗨,我昨天在这里回答了这个问题: How to bind object into iframe src

    您可以创建管道并使用 domsanitizer

    喜欢这个

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer} from '@angular/platform-browser';
    
    @Pipe({ name: 'safe' })
    export class SafePipe implements PipeTransform {
      constructor(private sanitizer: DomSanitizer) {}
      transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
      }
    } 
    

    然后将你的管道添加到应用模块

    @NgModule({
       declarations : [
         ...
         SafePipe
       ],
    })
    

    在 html 中你可以这样使用它(url 是你不安全的 url)

    <a href="{{url | safe}}">UNSAFE LINK</a>
    

    如果有帮助,请将我的答案标记为正确,谢谢!

    【讨论】:

    • 所以我需要通过搜索任何 URL 来编辑我的 HTML 字符串并用管道角度表达式替换它们?
    • 管道是最简单的方法,是的 url = 一个不安全的 url 请不要忘记标记答案 ;)
    • 嗯,在这种情况下,它更像是一种解决方法而不是解决方案......但也许没有解决方案,让我们看看是否有人想出了一个:)
    • 它没有解决方法,管道是你应该走的角度方式;)
    • 好吧,这里可能是个误会。您的提议将要求我直接更改我在编译时不知道的 HTML(在我的代码示例变量“a”中),因为它来自外部资源。我需要解析 HTML 并以编程方式用管道替换任何找到的 URL,这很 hacky。这将是在运行时从简单的 RichText 转换为 Angular 语法。我发现我在最初的问题中没有明确说明这一点并相应地更新它!
    猜你喜欢
    • 1970-01-01
    • 2019-12-03
    • 2019-05-18
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多