Search code examples
angularsanitization

unsafe value used in a resource URL context when loading local css file


I wonder if anyone can explain the meaning of the Dom Sanitisation in Angular2 in my case:

The img case is fine, it just werks. The stylesheet will trigger an error like in the title. What the what? Why? Anyone?

<img *ngIf="css" [src]="css" style="height:64px;margin-right:8px">
<link *ngIf="css" rel="stylesheet" [href]="css">

Solution

  • update

    DomSanitizationService is going to be renamed to DomSanitizer in RC.6

    original

    Images are safe. There is an <img> tag and that displays the image data, that's it. CSS can do much more. CSS can even add HTML https://developer.mozilla.org/en/docs/Web/CSS/::after which is quite insecure.

    To explicitly allow "unsafe" content use the sanitizer

    import {DomSanitizationService} from '@angular/platform-browser';
    
    return this.sanitizer.bypassSecurityTrustStyle(style);
    

    or use one of the other methods the sanitizer provides https://angular.io/docs/js/latest/api/platform-browser/index/DomSanitizationService-class.html

    See also https://stackoverflow.com/a/37076868/217408 for an example pipe that allows to apply the bypassSecurityXxx methods directly in bindings.