【发布时间】:2021-09-13 08:41:09
【问题描述】:
我有一个返回 JSON 的 Spring Boot 应用程序。
在它的一种方法中,它有一个Integer 参数(@RequestParam)。
在进行安全测试时,他们使用传入的一些 JS 代码调用了我的方法
(而不是整数值)。
2021-07-01 04:59:14.995 WARN [tpe-rcf,2ff110026bf0649e,2ff110026bf0649e,false] 12800
--- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver :
Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer';
nested exception is java.lang.NumberFormatException: For input string: "<script>alert(11355545)</script>"]
我在应用程序的控制台中收到上述错误。
然后以一些 JSON 格式将其发送到浏览器,如下所示:
{
...
"message": "Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"<script>alert(11355545)</script>\"",
"path": "/a/b/c"
}
我的问题是是否可以覆盖错误消息,例如通过将返回给浏览器的 JSON 中的 < 替换为 \u003c。
安全测试人员声称我应该清理返回的 JSON(即转义这些 < 符号),因为这可能会给旧版浏览器带来一些问题(即在其中执行此 JS 代码)。
但是产生错误信息的是SpringBoot框架,
我在这里没有太多控制权。
当然,我可以将参数定义为 String 并自己进行验证,但我怀疑这是正确的方法。我的参数定义为整数,我更喜欢保持这种状态。
所以我的问题是如何进行转义/清理?我尝试使用@ControllerAdvice 并覆盖ResponseEntityExceptionHandler,但到目前为止运气不佳。
我想如果有办法应该很简单。
最简单的方法是什么?
【问题讨论】:
-
这能回答你的问题吗? Spring Boot customize http error response?
-
看来你在处理 DefaultErrorAttributes。 SOF 上也有类似的回答。我已经分享了上面的链接。也许,这就是你所需要的。如果没有,你可以告诉我。我将尝试实施一些自定义项目来处理您的用例。
-
我会尝试并告诉你。确实似乎非常接近我的需要。
标签: java spring spring-boot