简体   繁体   中英

How to encode JSON/Ajax response for XSS?

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?

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.

一位同事向我指出,当我应该使用.text()时,我正在使用.html()呈现JSON数据,这是使用.createTextNode()的隐式方式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM