4
votes

I use DocumentsService to get an image file from the server after that I use URL.createObjectURL(result) to create image url from server respond, everything seem working fine but I keep get a error about sanitizing unsafe URL and can't see the image.

@Injectable()
export class DocumentsService {

    public url:string = 'api.server.url'

    constructor(private http: HttpClient , private dom: DomSanitizer) {
    }

    public getImageUrl(imageId: string): Observable<any> {

        let requestOptions = {
            params: {
                id: imageId
            },
            responseType: "blob"
        };

        return this._restClientService.get(this.url, requestOptions).map(result => {
            let url = URL.createObjectURL(result);
            return this.dom.bypassSecurityTrustUrl(url);   
        });
    }
}

In my component I have inject the service and

this._doc.getImageUrl(doc.id)
          .do(console.log) // => SafeUrlImpl {changingThisBreaksApplicationSecurity: "blob:http://localhost:4200/2b9b4820-c7d0-4920-a094-cb3e4cc47c7c"}
          .subscribe(url => this.photoUrl = url)
      }

in template I use a function to check if the use have image or not

public getImagePath(): string {
    if (this.photoUrl) {
      return this.photoUrl; //  after get the image from documents service
    }
    return FilesUrls.BlankAvatar;
  }

template

<img src="{{getImagePath()}}" alt="user image">

I keep get this error , I think I miss something

"WARNING: sanitizing unsafe URL value SafeValue must use [property]=binding: blob:http://localhost:4200/79dd8411-44a8-4e08-96d2-ad6d889c1056 (see http://g.co/ng/security#xss) (see http://g.co/ng/security#xss)"

4

4 Answers

5
votes

I think you don't return your SafeUrl after bypassSecurityTrustUrl.

Look at the version which works https://stackblitz.com/edit/angular-bqqumm

The code must like :

return this._restClientService.get(this.url, requestOptions).map(result => {
     let url = URL.createObjectURL(result);
     return this.dom.bypassSecurityTrustUrl(url);    
})
2
votes

I have found the problem is related to my template , I was using {{getImage Path()}} , according the error message I have to use property binding rather than interpolated string.

<img [src]="getImagePath()" alt="user image">
2
votes

When you use binding sanitizing is automatic, to set value using attribute you need to call DomSanitizer.sanitize with context SecurityContext.URL. By the way this is incorrect: src="{{getImagePath()}}" should be [attr.src]="getImagePath()"

0
votes

This is what worked for me when working with images giving me the same issues.

HTML:

<img [src]="currVerifiedLoanOfficerPhoto">

Component:

this.currVerifiedLoanOfficerPhoto = 'data:image/jpg;base64,' + (this.sanitizer.bypassSecurityTrustResourceUrl(item) as any).changingThisBreaksApplicationSecurity;