簡體   English   中英

使用DomSanitizer后,圖片網址仍然不安全

[英]Image url still unsafe after I use DomSanitizer

我使用DocumentsService從服務器獲取圖像文件之后,使用URL.createObjectURL(result)從服務器響應創建圖像URL,一切似乎都正常,但我仍然收到有關sanitizing unsafe URL的錯誤,並且看不到圖像。

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

在我的組件中,我注入了服務,

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

在模板中,我使用一個函數來檢查使用是否有圖像

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

模板

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

我不斷收到此錯誤,我想我錯過了一些事情

“警告:清理不安全的URL值SafeValue必須使用[property] = binding:blob: http:// localhost:4200 / 79dd8411-44a8-4e08-96d2-ad6d889c1056 (請參閱http://g.co/ng/security#xss )(請參見http://g.co/ng/security#xss )”

我認為您在bypassSecurityTrustUrl SafeUrl之后不會返回您的bypassSecurityTrustUrl

查看適用於https://stackblitz.com/edit/angular-bqqumm的版本

代碼必須像:

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

我發現問題與模板有關,我正在使用{{getImage Path()}} ,根據錯誤消息,我必須使用屬性綁定而不是插值字符串。

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

使用綁定自動DomSanitizer.sanitize時,要使用屬性設置值,您需要使用上下文SecurityContext.URL調用DomSanitizer.sanitize 順便說一句,這是不正確的: src="{{getImagePath()}}"應該是[attr.src]="getImagePath()"

這就是在處理圖像時給我帶來相同問題的方法。

HTML:

<img [src]="currVerifiedLoanOfficerPhoto">

零件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM