Escape EL in JSP that represent JSON data

被刻印的时光 ゝ 提交于 2019-12-12 19:39:12

问题


The Spring controller sets:

model.addAttribute("myJsonObj", JsonUtils.toJson(myObject));

The JSP has something like:

<script>
  var myObj = ${myJsonObj};
  (...)

How to properly protect this from any XSS exploit?

would break the JSON (double quotes, etc.)

What's the right strategy to avoid directly EL in the JSP?


回答1:


When JSP output var myObj = ${myJsonObj};, the behavior is the same as eval the script and cause XSS issue. The solution is output ${myJsonObj} as string, so malicious script will not execute. Then use JSON.parse() restore the string to javascript object, so you don't have to change other scripts.

You have to handle the double/single quote char when output ${myJsonObj} as string. This can be done using a JSP custom tag/EL function, for example:

var myObj = JSON.parse('<my:escapeEcmaScript value="${myJsonObj}"/>');

Or do it in Spring controller

model.addAttribute("myJsonObj", StringEscapeUtils.escapeEcmaScript(JsonUtils.toJson(myObject)));
//In JSP
//var myObj = JSON.parse('${myJsonObj}');


来源:https://stackoverflow.com/questions/35664551/escape-el-in-jsp-that-represent-json-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!