在Spring Boot MVC中添加ShallowEtagHeaderFilter

res*_*a87 2 etag spring annotations servlet-filters spring-boot

我正在尝试调整我的应用程序配置以设置ETag支持.

我刚刚检查了这个问题,所以让我说一下我的代码与它的不同之处:

  1. 我不使用任何xml配置文件.
  2. 我正在为系统的每个方面使用不同的配置类.我WebConfig看起来像这样:

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = { "xxx", "yyy" })
public class WebConfig extends WebMvcConfigurerAdapter {

   @Bean
   public Filter shallowETagHeaderFilter() {
        return new ShallowEtagHeaderFilter();
   }
      ...
}

  1. 我的SecurityConfig看起来像这样:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        ...

        @Override
        protected void configure(final HttpSecurity http) throws Exception {
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().exceptionHandling()
                        .authenticationEntryPoint(authenticationEntryPoint())
                .and().authorizeRequests()
                        .antMatchers(HttpMethod.GET, "/**").authenticated()
                        .antMatchers(HttpMethod.POST, "/**").authenticated()
                        .antMatchers(HttpMethod.HEAD, "/**").authenticated()
            .and().csrf().disable()    
            .addFilterBefore(authenticationTokenProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
        }

    }

  1. 我还有一个初始化类,它是空的:

    @Order(value=1)
    public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer {

    }

我没有看到任何地方ShallowEtagHeaderFilter被添加到默认链或任何东西,我如何在此设置中使用它?

res*_*a87 7

好的,

根据这篇文章:

[...]为了帮助缓解这种情况,Spring Security添加了缓存控制支持,它将在您的响应中插入以下标头.

Cache-Control:no-cache,no-store,max-age = 0,must-revalidate

Pragma:没有缓存

到期:0

所以,发生的事情是添加了ETag支持,但Spring Security在响应中使其失效.看来,如果要同时使用Spring Security和ETag支持,则需要声明以下代码行(由箭头突出显示):

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().exceptionHandling()
                    .authenticationEntryPoint(authenticationEntryPoint())
            .and().authorizeRequests()
                    .antMatchers(HttpMethod.GET, "/**").authenticated()
                    .antMatchers(HttpMethod.POST, "/**").authenticated()
                    .antMatchers(HttpMethod.HEAD, "/**").authenticated()
        .and().csrf().disable()    
        .addFilterBefore(authenticationTokenProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
        ===> http.headers().cacheControl().disable();
    }

}
Run Code Online (Sandbox Code Playgroud)