PUT and POST fail on unknown properties Spring different behavior

前端 未结 4 1582
野的像风
野的像风 2021-01-07 19:46

I am writing Spring Boot application using Spring Data Rest repositories and I want to deny access to resource if request body contains JSON that has unknown properties. Def

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-07 20:27

    When it creates new entity then it converts json directly to java entity object through deserialization process where required validation is involved. But when it updates existing entity then it converts json to JsonNode and then merge with existing entity and as expected no validation happens because it is feature for json deserialization to java object.

    As workaround you can additionally convert JsonNode to entity object and it will work as you expect.

    I did quick example how to gain required validation.

    go to https://github.com/valery-barysok/gs-accessing-data-rest

    It is not clear solution but you can improve it :)

    This example override existing spring class on classpath org.springframework.data.rest.webmvc.config.PersistentEntityResourceHandlerMethodArgumentResolver

    Note You must put this class on classpath before original version.

    I did copy-past this class to project and modified readPutForUpdate method:

    private Object readPutForUpdate(IncomingRequest request, ObjectMapper mapper, Object existingObject,
                                    RootResourceInformation information) {
    
        try {
    
            JsonPatchHandler handler = new JsonPatchHandler(mapper, reader);
            JsonNode jsonNode = mapper.readTree(request.getBody());
            // Here we have required validation
            mapper.treeToValue(jsonNode, information.getDomainType());
    
            return handler.applyPut((ObjectNode) jsonNode, existingObject);
    
        } catch (Exception o_O) {
            throw new HttpMessageNotReadableException(String.format(ERROR_MESSAGE, existingObject.getClass()), o_O);
        }
    }
    

    and i used application.properties file to configure DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES

提交回复
热议问题