Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image url still unsafe after I use DomSanitizer

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)"

like image 839
Muhammed Albarmavi Avatar asked Jan 03 '23 02:01

Muhammed Albarmavi


2 Answers

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);    
})
like image 57
Antoine V Avatar answered Feb 04 '23 12:02

Antoine V


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()"

like image 42
kemsky Avatar answered Feb 04 '23 12:02

kemsky