1

我将使用 Jackson Mapper 在 Spring MVC 中转义 HTML 以避免 XSS 攻击。

我寻找独自与杰克逊一起逃跑以及如何在春季配置杰克逊。
我尝试使用 "<" ">" 之类的文本导出 json,我希望将它们转义到&#60;&#62;

例如,我添加了一些用 "bold tag" 括起来的文本<b>,我希望在前端 html 中看到纯粗体标签文本,但最终文本在前端 html 页面中以粗体显示。

以下是我的方法,我不知道为什么它没有成功。

任何人都可以帮忙吗?

提前致谢!

public class CustomObjectMapper extends ObjectMapper {  
    public CustomObjectMapper() {
        this.getJsonFactory().setCharacterEscapes(new CustomCharacterEscapes());
    }
}

public class CustomCharacterEscapes extends CharacterEscapes {
    private final int[] asciiEscapes;

    public CustomCharacterEscapes() {
        int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
        esc['<'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['>'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['&'] = CharacterEscapes.ESCAPE_STANDARD;
        esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
        asciiEscapes = esc;
    }

    @Override
    public int[] getEscapeCodesForAscii() {
        return asciiEscapes;
    }

    @Override
    public SerializableString getEscapeSequence(int ch) {
        return null;
    }
}

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean id="jsonConverter"
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper">
                    <bean class="x.y.z.CustomObjectMapper" />
                </property>
            </bean>
        </array>
    </property>
</bean>

4

1 回答 1

0

我从未尝试过编写自己的 HttpMessageConverter,但我确实发现这篇文章似乎与您想要做的事情非常相关。在查看他们的解决方案与您在此处发布的内容时,我可以说我注意到的最大差异是您似乎没有实现/覆盖以下内容:

  1. 受保护的布尔支持(Class clazz),它指示您支持哪种类类型(如果您希望它足够通用以处理每种可能性,或者某些特定于您的域对象的类,我会在您的情况下进行侦察,这将是 Object 或 Serializable )
  2. protected Object readInternal(Class clazz, HttpInputMessage inputMessage),看起来它是用于请求端的
  3. protected void writeInternal(Object t, HttpOutputMessage outputMessage),看起来像是用于响应端

Another approach might be to simple create a custom Jackson serializer in conjunction with @ResponseBody. Or, better yet, if you have a value that is user-driven, and your storing it in a database, escape the values prior to insertion. That way you don't need to do anything at all, and the value(s) in question would be "safe" from end-to-end. If you wanted to get crazy-fancy, you could write a custom java.beans.PropertyEditor that escapes Strings for HTML and plug that into the mix using the InitBinder.

Finally, I would like to recomend that, instead of trying to replace the characters on your own, you use something like Apache Commons-Lang's StringEscapeUtils to escape the values.

于 2013-03-01T14:13:25.720 回答