Search code examples
angulartypescriptcaptchaunsafesanitize

Apply DomSanitizationService in Angular 6


Currently I have to support an Angular project.

There is an security issue report on unsafe image, the error message show under Chrome console is as follow:

unsafe:data:image/png;base64,:1 GET unsafe:data:image/png;base64, net::ERR_UNKNOWN_URL_SCHEME

I google around, and found that I need to use DomSanitizationService to sanitize the value. However, I keep having problem when code on it, I suspect is syntax error. The following is my HTML code:

<img src="{{ _DomSanitizationService.bypassSecurityTrustUrl(captchaSrc) }}"  height="auto" width="100%" id="captcha-img" />

And the following is my TypeScript file code:

import { DomSanitizer } from '@angular/platform-browser';

captchaSrc: string = 'data:image/png;base64,';

constructor(
    public _DomSanitizationService: DomSanitizer
  ) {
  }

this.captchaSrc += this.captcha.captchaImg;

I am having the following error in chrome console:

unsafe:SafeValue must use [property]=binding: data:image/png;base64, (see http://g.co/ng/security net::ERR_UNKNOWN_URL_SCHEME

Any ideas on what mistake I make?

***** Edit ***** After I refer Adrita Sharma answer, I still have some issue, which is I by pass in method, but it does not take effect:

startRegistration(via: string): void {
     this.sharedService.generateCaptcha().subscribe(response => {
     this.captcha = response;
     this.captchaSrc += this.captcha.captchaImg;
     this._DomSanitizationService.bypassSecurityTrustUrl(this.captchaSrc);
    });
}

Solution

  • Try like this:

    constructor( public _DomSanitizationService: DomSanitizer) {
       _DomSanitizationService.bypassSecurityTrustUrl(this.captchaSrc)
    }
    

    Template:

    <img [src]="captchaSrc" height="auto" width="100%" id="captcha-img" />
    

    EDIT:

    yourMethod(){
        this.captchaSrc = this._DomSanitizationService.bypassSecurityTrustUrl('data:image/png;base64,' + this.captchaSrc)
    }