How to html escape values by Jackson generator
We generate lots of JSON objects using Spring and its built-in MappingJacksonHttpMessageConverter . All great.
But now I want to html escape String values of my (any kind of) objects in order to prevent XSS.
So, how do i approach this problem? I first thought I could write a custom Object mapper and put it into the MappkingJacksonHttpMessageConverter. However, the writeValue takes an Object, and I don't want that, I want to have its fields to iterate over. Instead of doing that myself, I bet the jackson converter needs to do that as well. So i want to influence that part.
Now I end up with a SerializerProvider interface. The standard implementation (StdSerializerProvider) is getting called by the ObjectMapper. So somewhere there I want to override/influence the method that is responsible for setting values.
Is that possible? As far as I can see it is hard to extend. I cannot override the StdSerializerProvider to override the method that ObjectMapper uses. Perhaps I need to override another one?
Or, perhaps this is totally wrong and I need to approach it from a totally different angle?
Any thoughts?
Oh btw, implementing the SerializerProvider myself and creating a composit that delegates to the StdSerializerProvider, might be possible but I'd rather not to. (i already have problems instantiating the StdSerial开发者_JAVA技巧izerProvider myself).
Any thoughts are appreciated!
There are multiple ways, depending on how you can identify things you want to escape. Some thoughts:
- If you want to quote/escape all Strings, you could define custom String serializer
- You could first serialize as JSON tree (JsonNode) -- ObjectMapper.convertValue(pojo, JsonNode.class) -- modify it, then serialize to JSON (ObjectMapper.writeValue(intermediateTree))
- If you want a flexible system where you can add annotation for fields that need special handling, you could use Jackson 1.7 feature of ContextualSerializers; custom serializer that can reconfigure itself based on annotations. It may seem like an overkill at first, but this could be used to easily specify custom modifiers (annotation property with value of Class, that indicates object that serializer can call to modify value being serialized -- like escape)
This answer was given, while the question was about verifying that the string does not contains XSS and not escaping. This answer will not help you, if you want to escape the strings.
What about validating the created object (Command Object) with JSR 303 Bean Validation?
For example by using a not @NotHtml (annotation and validation) to the String properties of the "Command Object".
(Of course you have to implment the @NotHtml (@NotJavaScript or @NotXSS) Annotations and Validator by your selfe.)
精彩评论