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);
            }
        }
    }
  • 相关阅读:
    js 数组方法比较
    js 知识点
    vuex、redux、mobx 对比
    读SRE Google运维解密有感(二)
    读SRE Google运维解密有感(一)
    001_深度剖析什么是 SLI、SLO和SLA?
    006_mac osx 应用跨屏幕
    005_ss-link.info的ping探测工具
    015_sublime插件管理及所有非常有用插件
    001_软件waf
  • 原文地址:https://www.cnblogs.com/chong-zuo3322/p/12612331.html
Copyright © 2011-2022 走看看