Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 sanitize local drive url

I have tried using DomSanitizer methods to sanitize the following type of url with no success

C:\path\to\executable

Is there any way to sanitize this url to be used as href value?

Also I am binding the value with [] notation so I am sure it is not interpolated as string.

like image 236
Yakup Türkan Avatar asked Nov 09 '18 08:11

Yakup Türkan


1 Answers

First the url should be C:/path/to/executable not the one C:\path\to\executable

According to http://www.ietf.org/rfc/rfc2396.txt backslash characters are not valid characters in URLs

Most of the browsers convert the backslash into forward slashes. Technically, if you required backslash characters in your URL you need to encode them using %5C.

Now about the sanitization

You could just bind a function that returns safe url using bypassSecurityTrustUrl() in angular DomSanitizer

app.component.html

<a [href]="getlink()"> link  </a>

app.component.ts

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


export class AppComponent  {
  constructor(private sanitizer:DomSanitizer) {    }
  name = 'Angular';

  getlink():SafeUrl {
      return this.sanitizer.bypassSecurityTrustUrl("C:/path/to/executable");
  }
}

Recommended

Using Pipe: You can create a pipe to disable Angular’s built-in sanitization

safe.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

 public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
            case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
            case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
            case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
            case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
            case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
            default: throw new Error(`Invalid safe type specified: ${type}`);
        }
  }
}

NOTE : Don't forget to inject this pipe service in your app.module.ts

import { SafePipe } from './shared/safe-url.pipe';


@NgModule({ declarations: [SafePipe],...});

Now you can use the pipe to disable the built-in sanitization

 <a [href]="'C:/path/to/executable' | safe: 'url'"> link </a>

I would recommend using pipe as the code is reusable , also here is the working demo : https://stackblitz.com/edit/angular-vxcvfr

like image 170
Joel Joseph Avatar answered Sep 27 '22 19:09

Joel Joseph