how to sanitize url for angular 4

Viewed 20537

I'm trying to use the Object html tag to display a PDF that i made server side, but when i hard code the url it works and when i put it in a variable it gives me an Angular error and nothing is shown :

unsafe value used in a resource URL context

i tried using the sanitizer first but i read that it should be used only with tags that support href / src in my case it's data like this :

<object data="{{pdfSrc}}" type="application/pdf" width="100%" height="100%">

    </object><br>

Here is what i tried first :

pdfSrc: any =this.sanitizer.bypassSecurityTrustUrl('http://my_url.com') ;

thank you

4 Answers

I am adding an answer that builds on many comments and existing answers, because I had trouble finding the appropriate way to make things work.

First, I do not understand why most answers to this question use bypassSecurityTrustResourceUrl (here on SO or when googling), because we definitely don't want to bypass security, we want to sanitize an unsafe input! Using bypassSecurityTrustResourceUrl could make sense when the input was previously sanitized, but this should happen always at the last stage, and therefore if you do not know what you're doing, definitely do not bypassSecurity!

Tested in angular 13

EDIT: code becomes more complex to handle background image urls wrapped in "url(...)". But you can simplify it if you only need either img or background-image

# component.ts
import { DomSanitizer } from '@angular/platform-browser';

export class MyClass {
  constructor(private sanitizer: DomSanitizer)

  myUrl({ wrapInUrl = false }: { wrapInUrl?: boolean }={}): SafeResourceUrl | false {
    if(!this.event.bannerUrl) {
      return false;
    }
    const sanitized = this.sanitizer.sanitize(SecurityContext.URL, this.myUrl);
    return wrapInUrl
      ? `url(${sanitized})`
      : sanitized;
  }
}
<!-- component.html -->
<img
  [src]="myUrl()"
  *ngIf="myUrl()"
>
<div [style.background-image]="myUrl({wrapInUrl: true})">

As mentioned in previous answers (please give them credit as well), it is important to have exactly [src]="yourSanitizedValue" because feeding anything else (like a string interpolation) would remove the SafeResourceUrl type.

Related