I have SpringBoot application X that has customer facing APIs. Those APIs receive request body as JSON.
Application X issues API calls to application Y and receives responses with JSON body.
I want to prevent application X from receiving unknown fields in the request body on customer-facing controllers.
I was thinking about spring.jackson.deserialization.fail-on-unknown-properties=true but if I understand correctly such configuration will cause a failure also if a call from application X to application Y will return response body with unknown field. Therefore this configuration will make the API between application X and application Y more coupled and less robust.
I am looking for a way to enforce "fail-on-unknown-fields" only for deserialization of request body at customer facing controllers of an application while allowing deserialization at other parts of the application to ignore unknown fields
Example: I have the following customer facing API.
@PostMapping
public Response updateProduct(@RequestBody Product product) {
.....
}
Where
class Product {
private int id;
private String name;
private int price;
}
I want to prevent customer from passing the following body to request, because colour is not a know field.
{
"id": 777,
"name": "apple",
"price": 2,
"colour": "red"
}
But - I want it the "fail-unknown-fields" to be enforced on this controller only and not at other places where Jackson is used to deserialized responses received from other applications.
You can create a new
ObjectMapperinstance in your controller explicitly configuring itsDeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIESto the valuetruethat will force the fail in the case of unknown properties inside the json in the post request body like below:Choosing to convert the request body json to
Stringyou can configure manually yourObjectMapperlocal instance while you have to decide how to proceed when there is a json processing exception (in my case I simply decided to directly throw the exception but a different behaviour can be adopted) or theUnrecognizedPropertyExceptionexception like the case you presented.EDIT: answer the OP comment below
I am not aware if it is possible to do exactly what you want, but you can achieve something pretty similar: you can define a custom
ObjectMapperbean in your configuration class so having a default primary bean and your custom bean:Then in the same controller you can refer both the two beans, so one method will end with success because it works with the default primary bean and the other one will fail: