简体   繁体   中英

rails 3 escaped html tags unescaped in browser when served as JSON

I have a Rails 3.2 app that interacts with a 3rd party XML API for some data using ActiveResource. We want to ensure against XSS in that 3rd party XML, so we have enabled:

ActiveSupport.escape_html_entities_in_json = true 

This seems to work in for the XML data and converts the < tag in a potentially dangerous script call to &lt; like this:

&lt;script>alert('xss')&lt;/script>

(not sure why it only esacpes the lt TBH, but it seems to be by design)

Problem is that when I convert that XML to JSON & send to browser, the browser sees it as unescaped. The string in JSON that is sent to browser looks like this:

\u003Cscript\u003Ealert('xss')\u003C/script\u003E"

can anyone explain why the browser converts this back to the unescaped string, and suggest workarounds?

FWIW I'm using Backbone, Jquery, JST & EJS

If the string sent to the browser is like the one in the question, then it's not the browser converting it back, it's already sent unescaped. However, I don't think the server needs to encode it, as it's just data, sent in an intermediary data format which is JSON. It is correctly encoded for JSON. You have to be careful when you insert it into the DOM on the client though.

In the template, make sure you use <%- instead of <%= and it should be fine unless you are generating javascript code of some sort , but that's probably an edge case.

You can also choose to encode it in the response as you originally asked, in that case you should look into how it's converted from XML to JSON. Be aware though, that different contexts may need different encodings (especially encoding requirements for writing into plain HTML vs in a Javascript context are very different), and the server sending the data may not (want to) know what the client wants to do with it.

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