Preventing cross-site scripting attacks

A cross-site-scripting attack (XSS) is where an attacker manages to inject client-side script into a web page, when viewed by another user. This is particularly bad if the injected script makes a request to our server, because the server assumes that it is the authenticated user who is making the request and allows it.

There are a wide variety of forms in which XSS attacks can appear. The most common are where user-provided content is displayed without being properly escaped to prevent malicious HTML from being rendered. The next section explains how we can do this on the client, but you should also ensure that any user-provided content is sanitized on the server, before being stored or sent back to the client.

Securing HTML content in angularjs expressions

angularjs escapes all HTML in text that is displayed through the ng-bind directive, or template interpolation (that is text in {{curly braces}}). For example, using the following model:

$scope.msg = 'Hello, <b>World</b>!';

And the markup fragment looks as follows:

<p ng-bind="msg"></p>

The rendering process will escape the <b> tags, so they will appear as plain text, and not as markup:

<p>Hello, &lt;b&gt;World&lt;/b&gt;!</p>

This approach provides a pretty good defense against XSS attacks in general. If you actually want to display text that is marked up with HTML, then you must either trust it completely, in which case you can use the ng-bind-html-unsafe directive, or sanitize the text by loading the ngSanitizemodule, and then using the ng-bind-html directive.