Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

Angular security

The easiest way to understand why we need to bind to safeVideoUrls instead of the videos input property is by trying the videos array out. Replace the existing ngFor fragment HTML with the following:

<div *ngFor="let video of videos"> 
    <iframe width="198" height="132"  
[src]="'//www.youtube.com/embed/' + video" frameborder="0" allowfullscreen></iframe> </div>

And look at the browser's console log (a page refresh may be required). There are a bunch of errors thrown by the framework, such as:

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

No prize for guessing what is happening! Angular is trying to safeguard our application against a Cross-Site Scripting (XSS) attack.

Such an attack enables the attacker to inject malicious code into our web pages. Once injected, the malicious code can read data from the current site context. This allows it to steal confidential data and also impersonate the logged-in user, hence gaining access to privileged resources.

Angular has been designed to block these attacks by sanitizing any external code/script that is injected into an Angular view. Remember, content can be injected into a view through a number of mechanisms, including property/attribute/style bindings or interpolation.

Consider an example of binding HTML markup through a component model to the innerHTML property of an HTML element (property binding):

this.htmlContent = '<span>HTML content.</span>'    // Component

<div [innerHTML]="htmlContent"> <!-- View -->

While the HTML content is emitted, any unsafe content (such as a script) if present is stripped.

But what about Iframes? In our preceding example, Angular is blocking property binding to Iframe's src property too. This is a warning against third-party content being embedded in our own site using Iframe. Angular prevents this too.

All in all, the framework defines four security contexts around content sanitization. These include:

  1. HTML content sanitization, when HTML content is bound using the innerHTML property
  2. Style sanitization, when binding CSS into the style property
  3. URL sanitization, when URLs are used with tags such as anchor and img
  4. Resource sanitization, when using Iframes or script tags; in this case, content cannot be sanitized and hence it is blocked by default

Angular is trying its best to keep us out of danger. But at times, we know that the content is safe to render and hence want to circumvent the default sanitization behavior.