代码之家  ›  专栏  ›  技术社区  ›  Muhammed Albarmavi

使用domSanitizer后图像URL仍然不安全

  •  0
  • Muhammed Albarmavi  · 技术社区  · 6 年前

    我用 DocumentsService 在使用之后从服务器获取图像文件 URL.createObjectURL(result) 要从服务器response创建图像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必须使用 [属性]=绑定: 斑点: http://localhost:4200/79dd8411-44a8-4e08-96d2-ad6d889c1056 (见 http://g.co/ng/security#xss (见) http://g.co/ng/security_xss )

    3 回复  |  直到 6 年前
        1
  •  1
  •   kemsky    6 年前

    当使用绑定清理是自动的时,要使用需要调用的属性设置值 DomSanitizer.sanitize 随语境 SecurityContext.URL . 顺便说一下,这是不正确的: src="{{getImagePath()}}" 应该是 [attr.src]="getImagePath()"

        2
  •  2
  •   Antoine V    6 年前

    我想你不会还你的 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);    
    })
    
        3
  •  1
  •   Muhammed Albarmavi    6 年前

    我发现问题与我使用的模板有关 {{getImage Path()}} ,根据错误消息,我必须使用属性绑定,而不是插入字符串。

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