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 StdSerializerProvider myself).
Any thoughts are appreciated!
There are multiple ways, depending on how you can identify things you want to escape. Some thoughts:
EDIT: even better option, as pointed out by @Philzen, is use of
CharacterEscapes-> see https://www.cowtowncoder.com/blog/archives/2012/08/entry_476.html