angularangular-datatablesangular-dom-sanitizer

How to use DOMSANITIZER(bypassSecurityTrustUrl) while calling the API


Getting XSS vulnerabilities while calling the API for fetching the data. So trying to add DOMSANITIZER, but its failing. Tried below code, please suggest me the solution.

 this.http.get(this.domSanitizer.bypassSecurityTrustUrl(dataUrl),{headers:headers}).subscribe(response => {
      this.persons = response.data.map(x=>({...x,check:false,test:x.firstName}));
      this.dtTrigger.next();
    });

Stackblitz


Solution

  • You can use DOMSANITIZER while using the API in following way.

    1. Import these:
        import {
          Component,
          OnInit,
          ViewChild,
          SecurityContext,
        } from '@angular/core';
        
        import {DomSanitizer} from '@angular/platform-browser';
    
    1. Use this below code in your project where you are using this:
    const dataUrl = this.domSanitizer.sanitize(
          SecurityContext.RESOURCE_URL,
          this.domSanitizer.bypassSecurityTrustResourceUrl(
            'https://raw.githubusercontent.com/l-lin/angular-datatables/master/demo/src/data/data.json'
          )
        );
    
        this.http.get(dataUrl).subscribe((response) => {
          this.persons = response.data.map((x) => ({
            ...x,
            check: false,
            test: x.firstName,
          }));
          this.dtTrigger.next();
        });
    

    Important:

    This code is working on your stackblitz url.

    enter image description here

    I have also save it and you can go there to check it. https://stackblitz.com/edit/column-names-as-tooltip-wcw1f7?file=app%2Fapp.component.ts