使用Angular 2在受信任的HTML中运行脚本

Zev*_*ert 5 embed html-sanitizing angular

我有什么

我正在使用Angular 2构建个人博客应用。我的JSON文件中包含博客文章,该文件由服务器提供。

// Single post route
apiRouter.route("/post/:id")
    // Get a specific post
    .get((req: express.Request, res: express.Response) => {
        let post = blogData.posts.find(post => post.date === Number(req.params.id));
        res.json(post);
    })
);
Run Code Online (Sandbox Code Playgroud)

JSON博客数据文件中的各个条目如下所示:

"posts": [
  {
    "title": "Some Post's Title",
    "body": "Some post's body.",
    "date": 1481582451092,
    "headerImageName": ""
  },
  { ... }, ...
]
Run Code Online (Sandbox Code Playgroud)

在我的Web应用程序中,我希望有一个“博客帖子”打字稿组件,当访客在映射到单个帖子的路线上时显示一个单独的帖子。

我定义了一个简单的post数据类,如下所示:

export class PostData {
    body: string;
    date: number;
    imageFileName: string;
    title: string;
}
Run Code Online (Sandbox Code Playgroud)

显示帖子正文时,我将其通过此管道传递:

@Pipe({
    name: "trustPipe"
})
export class TrustPipe implements PipeTransform {

    constructor(@Inject(DomSanitizer) private sanitizer: DomSanitizer) { }

    transform(html: string): SafeHtml {
        return this.sanitizer.bypassSecurityTrustHtml(html);
    }
} 
Run Code Online (Sandbox Code Playgroud)

为了显示它,我编写了以下组件:

import { TrustPipe } from "./trust.pipe";

@Component({
    selector: "active-component",
    template: `
    <div class="card">
        <div *ngIf="post">
            <div class="card-title">
                <span>{{ post.title }}</span>
            </div>
            <div [innerHTML]="post.body | trustPipe"></div>
        </div>
    </div>`,
    styleUrls: ["styles/post.component.css", "styles/card.css"]
})
export class PostComponent implements OnInit {

    // Post is a superclass to PostData, it just provides
    // some helper functions on the base class, such as truncation
    // and a means of formatting dates
    post: Post;

    constructor(
        @Inject(BlogService) private blogService: BlogService,
        @Inject(ActivatedRoute) private activatedRoute: ActivatedRoute
    ) { }

    ngOnInit(): void {
        this.activatedRoute.params.forEach((params: Params) => {
            const id: number = +params["id"];
            this.blogService
                .getPost(id)
                .then(data => this.post = new Post(data));
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

这都是做什么的?

因此,重要的一点是,我有一些变体字符串(帖子正文为JSON),它代表我想作为子元素插入到DOM元素中的HTML部分。为此,我使用了该[innerHTML]属性并编写了一个Angular Pipe,bypassSecurityTrustHtml用于将字符串作为安全HTML信任。

怎么了?

脚本标签不执行。假设我写了一篇博客文章,其中嵌入了一些内容-就我而言,它可能是Github Gist,Instagram照片或Google相簿。我发现这是对的-脚本标记无法执行-以及使用Javascript 规避它的方法,但是我想知道angular是否可以像我正在尝试的那样插入HTML。我已经看到了的用法,ComponentFactory但不知道这是否是我想要的。我猜测这也会阻止我routerLinks在帖子的正文中使用。我可以为帖子正文编写子组件,但是如何动态换出模板?

问题

a)为什么Angular停止脚本运行?

b)还有其他方法可以运行脚本吗?

c)我是否应该为此使用其他设计模式-例如以HTML形式发布帖子?

shu*_*son 2

a) 安全性,特别是针对 XSS 的防护 - https://angular.io/docs/ts/latest/guide/security.html

b)是的,但要非常小心 - https://angular.io/docs/ts/latest/guide/security.html#!#bypass-security-apis

您是否尝试过绕过组件中的安全 API 而不是管道?您还使用什么安全上下文?

c) 您能否解析博客文章并将其保存为安全格式,或者您真的希望允许任何 js 在您的网站上运行吗?