【问题标题】:Tomcat valve forcing specific Cache-Control headersTomcat 阀强制特定的 Cache-Control 标头
【发布时间】:2019-05-17 22:34:55
【问题描述】:

我想在我的回复中正确设置 Cache-Control 和 ETag 标头。为此,我通过 spring 安全配置禁用了请求缓存:

httpSecurity.headers().cacheControl().disable();

那么当返回响应时:

ResponseEntity.ok()
        .header("Cache-Control", "max-age=60")
        .header("ETag", "my-tag")
        .build()

从某种意义上说,似乎没有返回默认的 spring security 缓存控制标头(默认情况下,我认为它们返回“no-cache,no-store,max-age=0,must-revalidate”)和我的标题出现在响应中。但是还有其他东西:

Cache-Control: private
Expires: Thu, 01 Jan 1970 00:00:00 GMT
ETag: "0.42.1-20181213080300000"
Cache-Control: max-age=60
...other headers

较低的缓存头是我的,但顶部的是不需要的。它们似乎来自org.apache.catalina.authenticator.AuthenticatorBase,这似乎是正在使用的嵌入式 Tomcat 的一部分。我一直无法找到访问和修改这个特定类的配置的方法。

请告知如何删除不需要的标题。

我在 Spring boot 1.5.18.RELEASE

【问题讨论】:

    标签: java spring-security tomcat8 tomcat-valve


    【解决方案1】:

    为了更改 Valve 的配置,我必须使用 EmbeddedServletContainerCustomizer 在适当的生命周期阶段从上下文中查找它,如下所示。

    @Component
    public class TomcatCacheControlCustomizer implements EmbeddedServletContainerCustomizer {
    
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            if(container instanceof TomcatEmbeddedServletContainerFactory){
                TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) container;
                containerFactory.addContextLifecycleListeners((LifecycleListener) event -> {
                    Context context = (Context) event.getLifecycle();
                    if(event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)){
                        if(context.getPipeline() != null){
                            Pipeline pipeline = context.getPipeline();
                            if(pipeline.getValves() != null){
                                Optional<Valve> authenticatorBase = Arrays.stream(pipeline.getValves()).filter(v -> v instanceof AuthenticatorBase).findFirst();
                                if(authenticatorBase.isPresent()){
                                    ((AuthenticatorBase) authenticatorBase.get()).setDisableProxyCaching(false);
                                }
                            }
                        }
                    }
                });
            }
        }
    
    }
    

    更新 AuthenticatorBase 的配置后,不需要的 Cache-Control 标头不再添加到响应中,只保留了我的自定义标头。

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 2015-04-13
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      相关资源
      最近更新 更多