我有一个简单的Java对象,我正在使用Jackson序列化为JSON,然后我将其放入JSP页面中的<script>标记中,作为初始化JavaScript对象的一部分。 例如
<script>SomeLib.load(${someObject});</script>除非 someObject的某个字段是包含"</script>"的字符串, 否则这很有效,因为这个问题 。 也就是说,如果输出看起来像这样:
<script>SomeLib.load({"someValue":"hacked!</script>"});</script>那么浏览器(到目前为止在Chrome和FF中都经过测试)在hacked!后认为</script>标签hacked! 正在关闭脚本标记。 这打破了JavaScript并让"});</script>对用户可见。
有没有办法让杰克逊以某种方式逃避这个价值来解决这个问题?
I have a simple Java object that I'm using Jackson to serialize to JSON, and then I'm dropping that into a <script> tag in my JSP page as part of initializing a JavaScript object. e.g.
<script>SomeLib.load(${someObject});</script>This works great unless one of the fields of someObject is a String that contains "</script>", because of this issue. That is, if the output looks like this:
<script>SomeLib.load({"someValue":"hacked!</script>"});</script>then the browser (tested in both Chrome and FF so far) believes the </script> tag after hacked! is closing the script tag. Which breaks the JavaScript and leaves "});</script> visible to the user.
Is there a way to get Jackson to escape that value in some fashion that will fix this problem?
最满意答案
拉维斯回答错了。 在那里看我的评论。
更好的方法是使用反斜杠转义斜杠</ :
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> ... <script>SomeLib.load(${fn:replace(jsonString, "</", "<\\/")});</script>注意:需要两个反斜杠,因此第一个在JSP语法中进行转义。
好的部分是,它不需要特殊的解码。
PS:要在杰克逊方面这样做,请参阅此博客 - 它涵盖了逃避其他角色,但只是在列表中添加斜线以逃避(全部)斜线字符。
Ravis answer is wrong. See my comment there.
A better way is to escape the slash in </ with a backslash, like:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> ... <script>SomeLib.load(${fn:replace(jsonString, "</", "<\\/")});</script>Note: two backslashes are needed so the first one is escaped in the JSP syntax.
The good part is, it needs no special decoding.
PS: To do it on Jackson side, see this blog - it covers escaping other characters, but just add slash to the list to escape (all) slash characters.
更多推荐
发布评论