Reputation: 39457
I have a spring boot app which returns JSON.
In one of its methods, it has an Integer
parameter (@RequestParam).
While doing security testing they called my method with some JS code passed in
(instead of an integer value).
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>"]
I am getting this error above in the console of my app.
This is then sent to the browser in some JSON which looks like this:
{
...
"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"
}
My question is if it's possible to override the error message e.g. by replacing the <
with \u003c
in the JSON that's returned to the browser.
The security testers claim I should sanitize the JSON returned (i.e. escape these <
symbols) since that may pose some issues for older browsers (i.e. get this JS code executed in them).
But it's the SpringBoot framework who generates the error message,
I have no much control here.
Of course I can define the parameter as String and do the validation myself but I doubt that is the right way. My parameter is defined as Integer and I prefer it stays that way.
So my question is how to do this escaping/sanitizing? I tried using @ControllerAdvice
and override ResponseEntityExceptionHandler
but no much luck so far.
I think if there's a way it should be quite simple.
What is the easiest way of doing this?
Upvotes: 1
Views: 1601
Reputation: 1527
I don't get why is @ControllerAdvice not working for you
This works perfectly fine for returning custom messages
@RestControllerAdvice(basePackages = {"your.package"})
public class CustomRestExceptionHandler {
@ExceptionHandler({MethodArgumentTypeMismatchException .class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<FooBarErrorEntity> methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
return new ResponseEntity<>(new FooBarErrorEntity(message, path),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Where FooBarErrorEntity can be your custom error entity, where you have the same attributes you'd expect normally Also you can parse the message and do the 'sanitizing' within the constructor of the ErrorEntity which would remove the duplicate code in case of more exceptions to handle
Upvotes: 2