2

I have an ASP.NET MVC2 website that uses Ajax and JSON heavily to load data from a database and populate HTML. I'd like to be able to encode the JSON object so that it renders any HTML as text rather than HTML. I was surprised to not find much discussion/obvious solutions for this, as this seems to be a big potential XSS issue.

Am I overlooking something, and there is a simple way to do this? Or do I need to come up with an in-house solution for this? If I do this myself, should I do it on the model, on the controller, or in the jquery?

Jerad Rose
  • 15,235
  • 18
  • 82
  • 153

2 Answers2

4

To protect against XSS, encode HTML as it gets output into the view. The data should remain raw (except for JSON encoding, which should be done automatically by your JSON library) in the JSON.

If you are requesting the JSON with JavaScript, and then inserting some of it into the document. Use document.createTextNode(String) to create a textNode from the data (which takes cares of characters with special meaning in HTML), then insert that textNode into the document.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

A colleague pointed out to me that I was using .html() to render the JSON data, when I should have been using .text(), which is an implicit way of using .createTextNode().

Jerad Rose
  • 15,235
  • 18
  • 82
  • 153