如何在Spring RESTful中创建过滤器以防止XSS?

1 xss rest spring spring-java-config

我使用Spring 4.2.6.RELEASE和后端是休息服务.现在我无法使用Prevent XSS过滤器

我的过滤器是:

@Component
@Order(1)
public class XSSFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }

  @Override
  public void destroy() {
  }

  @Override
  public void doFilter(
        ServletRequest request, 
        ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {

      chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
   }

}
Run Code Online (Sandbox Code Playgroud)

和XSSRequestWrapper是:

public class XSSRequestWrapper extends HttpServletRequestWrapper {

  public XSSRequestWrapper(HttpServletRequest servletRequest) {
    super(servletRequest);
  }

  @Override
  public String[] getParameterValues(String parameter) {
    String[] values = super.getParameterValues(parameter);

    if (values == null) {
        return null;
    }

    int count = values.length;
    String[] encodedValues = new String[count];
    for (int i = 0; i < count; i++) {
        encodedValues[i] = stripXSS(values[i]);
    }

    return encodedValues;
  }

  @Override
  public String getParameter(String parameter) {
    String value = super.getParameter(parameter);

    return stripXSS(value);
  }

  @Override
  public String getHeader(String name) {
    String value = super.getHeader(name);
    return stripXSS(value);
  }

  private String stripXSS(String value) {

    return StringEscapeUtils.escapeHtml(value);
  }
}
Run Code Online (Sandbox Code Playgroud)

并在WebConfig中扩展WebMvcConfigurerAdapter类:

// -----------------------------------------------------
// Prevent XSS
// -----------------------------------------------------

@Bean
public FilterRegistrationBean xssPreventFilter() {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();

    registrationBean.setFilter(new XSSFilter());
    registrationBean.addUrlPatterns("/*");

    return registrationBean;
}
Run Code Online (Sandbox Code Playgroud)

我的休息班是:

@RestController
@RequestMapping("/personService")
public class PersonController extends BaseController<PersonDto, PersonCriteria> {

  @RequestMapping( value= "/test" )
  private void getTest2(@RequestParam String name) {

      System.out.println(name);

      System.out.println( StringEscapeUtils.escapeHtml(name) );

  }

}
Run Code Online (Sandbox Code Playgroud)

但它不起作用,没有任何错误或异常.我该怎么做并创建自己的过滤器?我只使用Java Config而不使用XML.在我的控制器中,我被迫再次使用StringEscapeUtils.escapeHtml(名称),这很糟糕.

Meh*_*ebi 10

我已根据您的代码创建了一个完全可执行的示例项目.

一切顺利,您可以从我的github https://github.com/mehditahmasebi/spring/tree/master/spring-xss-filter下载完整的源代码,并运行命令"mvnw spring-boot:run",并在浏览器类型中:http:// localhost:8080/personService/test?name = foobar,因此您可以在XSSRequestWrapper.stripXSS中看到结果.

我希望这个源代码能帮到你.


一些解释:

项目结构:

  • 的pom.xml
  • 用于Spring web配置的WebConfig.java
  • SpringBootApplication.java用于启动应用程序
  • 你的类(PersonController.java,XSSFilter.java和XSSRequestWrapper.java)

潜入他们,但我只是复制重要的行:

的pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)

WebConfig.java(在底线你可以看到你的bean):

@Configuration
@EnableWebMvc
@EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    @Override
    protected void configure(HttpSecurity http) throws Exception {      
        http
            .authorizeRequests()
                .anyRequest().permitAll()
            .and().csrf().disable();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowCredentials(true)
        .allowedHeaders("*")
        .allowedMethods("GET, POST, PATCH, PUT, DELETE, OPTIONS")
        .allowedOrigins("*");
    }

    @Bean
    public FilterRegistrationBean xssPreventFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();

        registrationBean.setFilter(new XSSFilter());
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }
}
Run Code Online (Sandbox Code Playgroud)

SpringBootApplication.java(用于启动项目):

@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer {

    /**
     * tomcat deployment needed
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringbootApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
        System.out.println("Spring boot application started!");

    }
}
Run Code Online (Sandbox Code Playgroud)

其他java源文件与您完全一样,但有2个更改:

首先,我添加了一个sysout行来查看代码的跟踪而无需调试:

private String stripXSS(String value) {
    if(value != null)
        System.out.println("escapeHTML work successfully and escapeHTML value is : " + StringEscapeUtils.escapeHtml(value));
    return StringEscapeUtils.escapeHtml(value);
}
Run Code Online (Sandbox Code Playgroud)

第二个变化是,我从PersonController评论了escapeHtml,正如你所说的不是一个好主意:

  @RequestMapping( value= "/test" )
  private void getTest2(@RequestParam String name) {

      System.out.println(name);

//      System.out.println( StringEscapeUtils.escapeHtml(name) );

  }
Run Code Online (Sandbox Code Playgroud)

您可以在我的github上找到所有来源https://github.com/mehditahmasebi/spring/tree/master/spring-xss-filter