Dynamic URLS

**This blog post is just one part of a series of Angular tutorials & advanced topics. Make sure you have a look!

Dynamic URLs

We will start by defining a dynamic URL as a pointer to an address somewhere on the web that can or will be changed at runtime (on our webpage) dynamically and is not hardcoded.

We will often need to use dynamic URLs in our application, such as an image source, iframe, or any other content that we would like to display or navigate to according to the interaction with our user in the HTML or some other dynamic roles. If you will try to bound the URL to the component property such as

<a href="{{some_dynamic_link}}"> or <a [href]="some_dynamic_link"> 

You will probably end up with the following exception in your console :

Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)

The idea that stands behind this safety exception is to prevent XSS, we wouldn’t want attackers to find a vulnerability in our HTML code, then attack it by injecting malicious code to our DOM. A smart attacker can change the URL resource to a script resource so it can collect data from our app or any other malicious act that he or she desires. Angular by default will just block unsafe URLs (dynamic URLs) – protecting us from making some unaware mistakes.

How can we still use safe dynamic URLs in our code?

Sanitization is the inspection of an untrusted value, turning it into a value that is safe to insert into the DOM. In many cases, sanitization does not change a value at all. Sanitization depends on the context it is used: a value that is harmless in CSS is potentially dangerous in a URL.

Angular defines four security contexts—HTML, style, URL, and resource URL:

  • HTML is used when interpreting a value as HTML, for example, when binding to innerHtml
  • Style is used when binding CSS into the style property
  • URL is used for URL properties such as
  • Resource URL is a URL that will be loaded and executed as code.(from Angular 2 official site).

DomSanitizer

Calling any of the bypassSecurityTrust APIs disables Angular’s built-in sanitization for the value passed in. Carefully check and audit all values and code paths going into this call. Make sure any user data is appropriately escaped for this security context. *For more detail check out the Security Guide.

The Angular way to sanitize

First, inject the DomSanitizer service in your component

constructor(private sanitizer: DomSanitizer) {}

Now the DomSanitizer service can sanitize your URL:

getSantizeUrl(url : string) { 
    return this.sanitizer.bypassSecurityTrustUrl(url); 
}

In the HTML we will bind the URL as in this example

<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />
 </img>

Angular will now permit us to use dynamic URLs in our HTML template. Please note that we have different sanitize functions for different purposes so first, you will need to understand what issue you are addressing and then use the correct function accordingly.

class DomSanitizer { sanitize(context: SecurityContext, value: any) : string bypassSecurityTrustHtml(value: string) : SafeHtml bypassSecurityTrustStyle(value: string) : SafeStyle bypassSecurityTrustScript(value: string) : SafeScript bypassSecurityTrustUrl(value: string) : SafeUrl bypassSecurityTrustResourceUrl(value: string) : SafeResourceUrl }

Wait… We are not finished yet

Please notice that it is bad practice to add a function call directly in your HTML template as suggested above since it will run each time the change detection fires. This will probably cause performance issues. The correct way to address this problem is by using a custom pipe and making sure we declare it as a pure pipe so Angular will cache our result and will not sanitize the URL every time the change detection fires.


class SanitizerPipe {

  constructor(private sanitizer: DomSanitizer) {}

  transform(url: string): string {
      if(!url) return null;
      return this.sanitizer.bypassSecurityTrustUrl(url);

  }
}

Now the pure pipe will sanitize the URL once and cache it for farther use.

**This blog post is just one part of a series of Angular tutorials & advanced topics. Make sure you take a look!

references:
https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
https://angular.io/docs/ts/latest/guide/security.html#!#xss

Angular 2 – dynamic URLs Sanitizer

Also published on Medium.

Yoni Amishav


Tech lead, blogger, node js Angular and more ...


Post navigation


7 thoughts on “Angular 2 – dynamic URLs Sanitizer

  1. I’m trying to use similar approach for setting src of with a base64 data url. However, it’s not working! Any ideas?

  2. Hi, isn’t bypassSecurityTrustUrl just ignoring it instead of sanitizing? Also, instead of a value what if is a complex object?

    1. what do u mean by complex object? can u provide an example, to the question – dont use it to external code as WARNING: calling this method with untrusted user data exposes your application to XSS security risks!

Leave a Reply

Free Email Updates
Get the latest content first.
We respect your privacy.
%d