Search code examples
angularsecuritytemplatesinline-styles

Displaying Images in Angular 6 Templates Thru Inline Styles - Security Issues


I need to display an image via an inline style. The image is not local, rather it's a URI from a JSON feed. However, I cannot get past Angular 6 security in spite of following the official docs. I've checked the image URI and it's good.

Console Output:

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

Rather than go through everything I've tried, here's what I currently have. I cannot be the only one who faced this issue, so I'd like to know how anyone else did it?

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);
  }
}

template syntax:

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

Logging trustedURL to the console informs me SafeValue requires property binding. Is that not what I'm doing? Here's that warning:

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

Solution

  • sanitize the URL from the component

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

    And add to the template

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