cn.twelvet.xss.XssAutoConfiguration Maven / Gradle / Ivy
package cn.twelvet.xss;
import cn.twelvet.xss.config.XssProperties;
import cn.twelvet.xss.core.*;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* jackson xss 配置
*
* @author twelvet
*/
@AutoConfiguration
@EnableConfigurationProperties(cn.twelvet.xss.config.XssProperties.class)
@ConditionalOnProperty(prefix = cn.twelvet.xss.config.XssProperties.PREFIX, name = "enabled", havingValue = "true",
matchIfMissing = true)
public class XssAutoConfiguration implements WebMvcConfigurer {
private final XssProperties xssProperties;
/**
* @param xssProperties XssProperties
*/
public XssAutoConfiguration(XssProperties xssProperties) {
this.xssProperties = xssProperties;
}
/**
* @param properties XssProperties
* @return XssCleaner
*/
@Bean
@ConditionalOnMissingBean
public XssCleaner xssCleaner(XssProperties properties) {
return new DefaultXssCleaner(properties);
}
/**
* @param properties XssProperties
* @param xssCleaner XssCleaner
* @return FormXssClean
*/
@Bean
public FormXssClean formXssClean(XssProperties properties, XssCleaner xssCleaner) {
return new FormXssClean(properties, xssCleaner);
}
/**
* @param properties XssProperties
* @param xssCleaner XssCleaner
* @return Jackson2ObjectMapperBuilderCustomizer
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer(XssProperties properties, XssCleaner xssCleaner) {
return builder -> builder.deserializerByType(String.class, new JacksonXssClean(properties, xssCleaner));
}
/**
* @param registry InterceptorRegistry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
List patterns = xssProperties.getPathPatterns();
if (patterns.isEmpty()) {
patterns.add("/**");
}
XssCleanInterceptor interceptor = new XssCleanInterceptor(xssProperties);
registry.addInterceptor(interceptor)
.addPathPatterns(patterns)
.excludePathPatterns(xssProperties.getPathExcludePatterns())
.order(Ordered.LOWEST_PRECEDENCE);
}
}