Mastering Web Application

(Rick Simeone) #1

Securing Your Application


And the markup fragment looks as follows:


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

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


<p>Hello, <b>World</b>!</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 ngSanitize module, and then using the ng-bind-
html directive.


Allowing unsafe HTML bindings

The following binding will render the tags as HTML to be interpreted by
the browser:


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

Sanitizing HTML

AngularJS has one more directive that will selectively sanitize certain HTML tags,
while allowing others to be interpreted by a browser, which is ng-bind-html. Its
usage is similar to the unsafe equivalent:


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

In terms of escaping, the ng-bind-html directive is a compromise between behavior
of ng-bind-html-unsafe (allow all HTML tags) and ng-bind (allow no HTML tags
at all). It might be a good option for cases where we want to allow some HTML tags
to be entered by users.


The sanitization uses a whitelist of safe HTML tags, which is quite
extensive. The main tags that will be sanitized include the <script>
and <style> elements, as well as attributes that take URLs such as
href, src, and usemap.

The ng-bind-html directive resides in a separate module (ngSanitize), and
requires inclusion of an additional source file: angular-sanitize.js. You must
declare a dependency on the ngSanitize module if you plan to use the ng-bind-
html directive, as shown in the following code: