通过内联样式在Angular 6模板中显示图像-安全问题

时间:2018-12-21 11:40:44

标签: angular security templates inline-styles

我需要通过内联样式显示图像。图片不是本地的,而是JSON提要中的URI。但是,尽管遵循了官方文档,但我仍无法超越Angular 6安全性。我检查了图像URI,它很好。

控制台输出:

Object { changingThisBreaksApplicationSecurity: "http://uri/to/image.png" }

这是我目前所拥有的,而不是经历我尝试过的所有事情。我不是唯一一个遇到此问题的人,所以我想知道其他人是怎么做到的?

component.ts:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
import { DataService } from '../../services/data.service';
import { Business } from '../../models/Business';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html'
})
export class ListComponent implements OnInit {
  fetchedBusinesses: Business[];
  trustedURL: any;

  constructor(private dataService: DataService, private sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.fetchedBusinesses = this.dataService.getBusinesses();
    this.trustedURL = this.sanitizer.bypassSecurityTrustUrl(this.fetchedBusinesses[0].backgroundImageURL);
  }
}

模板语法:

<div class="someClass" *ngFor="let biz of fetchedBusinesses">
    <div class="someClass" [style.background]="'url(' + trustedURL + ')'"></div>
</div>

在控制台上登录trustedURL会告诉我SafeValue需要属性绑定。那不是我在做什么吗?这是警告:

WARNING: sanitizing unsafe style value url(SafeValue must use [property]=binding: http://path/to/image.png (see http://g.co/ng/security#xss)).

1 个答案:

答案 0 :(得分:2)

清理组件中的URL

this.image = this.sanitization.bypassSecurityTrustStyle(`url(${this.fetchedBusinesses[0].backgroundImageURL})`); 

并添加到模板

<div class="someClass" [style.background]="image"></div>