Chapter 7
angular.module('expressionsEscaping', ['ngSanitize'])
.controller('ExpressionsEscapingCtrl', function ($scope) {
$scope.msg = 'Hello, <b>World</b>!';
});
The ng-bind-html directive uses the $sanitize service, which is also found inside
the ngSanitize module. This service is a function that takes a string, and then
returns a sanitized version of the string, as described in the following code:
var safeDescription = $sanitize(description);
Unless you are working with any existing legacy systems (For example
CMS, back-ends sending HTML, and so on), markup in the model
should be avoided. Such markup can't contain AngularJS directives and
requires the ng-bind-html-unsafe or ng-bind-html directive to
obtain the desired results.
Preventing the JSON injection vulnerability
There is a JSON injection vulnerability that allows evil third party websites to
access your secure JSON resources, if they return JSON arrays. This is done by
effectively loading the JSON as a script in a web page, and then executing it. See
http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-
vulnerability.aspx.
The $http service has a built-in solution to protect against this. To prevent the
browser from being able to execute the JSON returned from the secure resource,
you can arrange for your server to prefix all the JSON requests with the ")]}',\n"
string, which is not legal JavaScript, and so cannot be executed. The $http service
automatically strips this prefix string, if it appears from any JSON response. For
example, if your JSON resource returns the following array:
['a,'b','c']
This is vulnerable to the JSON injection attack. Instead, the server should return:
)]}',
['a','b','c']
This is not valid JavaScript. It cannot be executed by the browser, and so is no longer
vulnerable to attack. The $http service will automatically strip off this invalid prefix,
if found, before returning the valid JSON in its response object.