Spring JSON tainting response from JacksonMessageConverter

馋奶兔 提交于 2019-12-08 09:03:17

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/9727096/spring-json-tainting-response-from-jacksonmessageconverter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!