Escape EL in JSP that represent JSON data

2019-07-15 04:50发布

问题:

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}');