javaspring-bootcache-control

How do I add Cache-Control with no-cache and no-store header in Spring Boot?


I have Spring Boot 3.0.4 application and I have tried many things to add Cache-Control with no-store but either nothing happens or it says that headers or something is both enabled and disabled and gives me error. I have tried the following method but it doesn't show me Cache-Control headers in the response.

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.defaultsDisabled().disable()) // <-- I have added this line without help
                .csrf().disable()
                .securityMatcher(protectedPaths.toArray(new String[0]))
                .authorizeHttpRequests(requests -> requests.anyRequest().authenticated())
                .oauth2ResourceServer()
                .jwt(customizer -> customizer.jwtAuthenticationConverter(new UserAuthenticationTokenConverter()));
        return http.build();
    }

}

What I am doing wrong?


Solution

  • import jakarta.servlet.*;
    import jakarta.servlet.http.HttpServletResponse;
    import org.springframework.core.Ordered;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    import org.springframework.web.util.ContentCachingResponseWrapper;
    
    import java.io.IOException;
    
    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class LogRequestHandler implements Filter {
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            ContentCachingResponseWrapper responseCacheWrapperObject = new ContentCachingResponseWrapper((HttpServletResponse) servletResponse);
            filterChain.doFilter(servletRequest, responseCacheWrapperObject);
            responseCacheWrapperObject.addHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
            responseCacheWrapperObject.copyBodyToResponse();
        }
    }