zoukankan      html  css  js  c++  java
  • springboot防止xss攻击

    pom.xml:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    
    <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    
    <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    java代码:

    import java.io.IOException;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
    import org.springframework.web.util.HtmlUtils;
    
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.databind.JsonSerializer;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.module.SimpleModule;
    
    /**
     * XSS防护配置<br/>
     *
     */
    @Configuration
    public class XssConfig {
        /**
         * XSS防护<br/>
         * 
         * @param builder
         * @return
         */
        @Bean
        @Primary
        public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
            // 解析器
            ObjectMapper objectMapper = builder.createXmlMapper(false).build();
            // 注册xss解析器
            SimpleModule xssModule = new SimpleModule("XssStringJsonSerializer");
            xssModule.addSerializer(new XssStringJsonSerializer());
            objectMapper.registerModule(xssModule);
            // 返回
            return objectMapper;
        }
    }
    
    
    class XssStringJsonSerializer extends JsonSerializer<String> {
    
        @Override
        public Class<String> handledType() {
            return String.class;
        }
    
        @SuppressWarnings("unused")
        @Override
        public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                throws IOException {
            if (value != null) {
                String encodedValue = HtmlUtils.htmlEscape(value);
                jsonGenerator.writeString(value);
            }
        }
    }
  • 相关阅读:
    我来说说博客评论的事
    SWFUpload+Javascript仿163邮件上传文件
    如何暂停和终止线程
    分享我的数据处理类库,欢迎拍砖
    求数列两两之差,再求和
    poj 1006 中国剩余定理
    Poj算法做题顺序
    poj 1328
    ZOJ 3279
    poj 2352 树状数组
  • 原文地址:https://www.cnblogs.com/chong-zuo3322/p/12612331.html
Copyright © 2011-2022 走看看