You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.0.4添加no-cache/no-store的Cache-Control头失败,求排查

解决Spring Boot 3.0.4中Cache-Control: no-store头不生效的问题

你当前的配置存在两个核心问题:

  • 调用headers.defaultsDisabled().disable()直接关闭了Spring Security的整个Headers模块,不仅不会生成你需要的Cache-Control头,连其他安全相关的响应头也会被禁用
  • 仅禁用默认配置,但没有主动定义并启用Cache-Control的规则

修正后的Security配置

替换你当前的headers配置段,保留Headers模块并自定义Cache-Control规则:

import java.util.List;

@Configuration
@EnableWebSecurity
public class ResourceServerConfig {

    private final List<String> protectedPaths = List.of(
            "/users/*/**",
            "/api/**",
            "/admin/**"
    );

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .headers(headers -> headers
                        .cacheControl(cache -> cache
                                .cacheControl(CacheControl.noStore()) // 配置no-store规则
                        )
                )
                .csrf().disable()
                .securityMatcher(protectedPaths.toArray(new String[0]))
                .authorizeHttpRequests(requests -> requests.anyRequest().authenticated())
                .oauth2ResourceServer()
                .jwt(customizer -> customizer.jwtAuthenticationConverter(new UserAuthenticationTokenConverter()));
        return http.build();
    }

}

全局生效的补充方案

如果需要让Cache-Control: no-store对所有请求路径(包括非保护路径)生效,可以通过WebMvcConfigurer做全局配置:

@Configuration
public class WebGlobalConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                response.setHeader("Cache-Control", "no-store");
            }
        }).addPathPatterns("/**");
    }
}

注意:不要同时混用Spring Security的headers配置和WebMvc全局配置,避免出现重复响应头的冲突问题。

内容的提问来源于stack exchange,提问作者ilhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:34:51