Question

I have a JacksonMessageConverter in my Spring application for returning JSON response. But before the JSON is returned, I would like to taint the JSON as given in Ajax Security - Preventing JSON hijacking. Is it possible to do so when using a message converter?

Update

Am looking for a solution similar to this spring prefixjson with responsebody but I already have the configuration set up correctly. PFB

<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="prefixJson" value="true" />
    <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter"/>
        </list>
    </property>
</bean>

But still the returned JSON is not prefixed with "&&{}".

NOTE : I would like to use a different prefix for the JSON as explained in Ajax Security - Preventing JSON hijacking but even the default support provided in Jackson does not seem to work. Any ideas?

Was it helpful?

Solution

Try to debug MappingJacksonHttpMessageConverter to see, if prefixJson equals true. If not, then your bean not injected propely. If yes, look in the writeInternal() method of MappingJacksonHttpMessageConverter class. IT clearly do what you need:

try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("{} && ");
        }
        this.objectMapper.writeValue(jsonGenerator, o);
    }

If you want to add custom prefix, you need to override writeInternal() and do it there.

OTHER TIPS

Easier approach would be to extend MappingJacksonHttpMessageConverter and override writeInternal method to do stuff like custom prefixing,etc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top