Defenses against XSS
HTML encoding as defense
The preferred defense is to use the encoding libraries that come with your web framework. That is, most web frameworks have built-in libraries that will HTML-encode user-supplied data like this:
As with the previous example, the solution here is to use our web framework’s HTML encoding library. Proper encoding would result in markup like this:
<img src="picture.jpg" alt="blah" onload="$('#submitbutton').click();" />
The quotes are replaced by
" so the onload is just part of the alt text instead of a new attribute. The HTML encoding prevents the attack.
Handling attacker-controlled data in other contexts
XSS by way of AngularJS expression injection doesn’t need
>, so traditional web framework escaping doesn’t help. In general, you shouldn’t need to allow dynamic content inside of a dom element that’s decorated with the ng-app attribute. But if for some strange reason you do, be sure to encode the
}} so that attackers can’t inject an AngularJS expression.
In the next lesson, we’ll get an introduction to another vulnerability, cross-site request forgery.