Reputation: 31
I am using a Spring boot application and there is a requirement to enable security by disabling the caching between the web-pages. As I understand, by default, Spring Security sets specific cache-control header values for us, without us having to configure anything.
But for my web application, the following response headers are not present. Cache-Control", "no-store" Pragma", "no-cache" Expires", "0" I have tried setting them using an interceptor(implementing HandlerInterceptor) and adding the following code in the preHandle, postHandle and afterCompletionMethod.
response.setHeader("Cache-Control", "no-store"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
Although the control comes to these methods and the header is set, when I inspect the web-browser, I don't see these headers.
What could be the reason?
Upvotes: 3
Views: 4644
Reputation: 73
There are different types of setting the header.
I would suggest to set it either with a filter or the configuration.
Configuration
By default spring-boot sets security headers. With the .defaultsDisabled() you disable them and can selective activate the wanted headers.
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.headers()
// do not use any default headers unless explicitly listed
.defaultsDisabled()
.cacheControl();
}
}
Will set the header to following settings:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
For more detail of the configuration here is the doc. https://docs.spring.io/spring-security/site/docs/4.0.x/reference/html/headers.html
Alternative you can use a filter.
Filter
@WebFilter("/filter-response-header/*")
public class AddResponseHeaderFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader(
"Cache-Control", "no-store");
httpServletResponse.setHeader(
"Pragma", "no-cache");
httpServletResponse.setHeader(
"Expires", "0");
chain.doFilter(request, response);
}
For a single response
HttpServletResponse:
HttpServletResponse response
response.addHeader("Cache-Control", "no-store");
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "0");
for more have a look here: https://www.baeldung.com/spring-response-header
Upvotes: 5