防xss攻击,需要对请求参数进行escape吗?
先看一个测试:
请求:
http://localhost:8080/testapi/testapi?apiPath=http%3A%2F%2Fhbjltv.com%2Finfo%2Frequest%3Fusername%3Dhuang%26password%3Dadmin
解码之后就是:
http://localhost:8080/testapi/testapi?apiPath=http://hbjltv.com/info/request?username=huang&password=admin
该接口用于测试协作方接口的应答状态码.
为了防止xss攻击,所以对所有参数都进行html escape:
@RequestMapping("/testapi")
@ResponseBody
public String test(String apiPath, String requestMethod) throws IOException {
apiPath = HtmlUtils.htmlEscape(apiPath);
URL url = new URL(apiPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
httpUrlConnection.setDoInput(true);
httpUrlConnection.setUseCaches(false);
if (!ValueWidget.isNullOrEmpty(requestMethod)) {
httpUrlConnection.setRequestMethod(requestMethod);
}
httpUrlConnection.connect();
int responseStatusCode = httpUrlConnection.getResponseCode();
httpUrlConnection.disconnect();
System.out.println("responseStatusCode:" + responseStatusCode);
Map<String, Object> map = new HashMap<String, Object>();
map.put("responseCode", responseStatusCode);
map.put("apiPath", apiPath);
return HWJacksonUtils.getJsonP(map);
}
看看协作方接口收到的参数:
我传递的参数名称明明是password,但是现在怎么变成了amp;password ?
因为:
apiPath = HtmlUtils.htmlEscape(apiPath);
所以对参数进行HTML escape时应该不处理&
修改HTML escape 的函数如下: