In this article of Spring security tutorial, we will inspect the Spring Security cache control headers. We will look at the default behavior of Spring security along with a way to change the cache control headers in Spring Security.
Spring Security Cache Control Headers
Security involves a lot of precautions to save the data. There are certain default headers added by Spring security to disable caching to protect user content. Cache control headers provide a lot of benefits, which include:
- Cache data locally by browser to avoid network hops.
- Low latency.
- Lower server load by serving content stores locally in the browsers.
By effectively using the spring security cache control headers, it will help us achieve the above mentioned goals. Spring security provides flexibility to override the headers set by Spring security to allow caching static contents (like CSS, JavaScript etc.). Run our Spring security application available on the GitHub repository and open the login page. If you check the HTTP Request, the resulting cache-control
header will look like this:
Here is the default cache-control
header added by Spring security:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Keep in mind, if our application provides these headers with some other values, Spring security cache control headers will be back out of the way and will let our custom defined headers take precedence.
1. Disabling Cache Control Headers
Spring security provides complete control to on these cache control headers. In case we want to disable these cache control headers in HTTP response, we can easily do that using our security configuration class:
@EnableWebSecurity
public class AppSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
http
.headers(headers -> headers
.cacheControl(cache -> cache.disable())
);
}
}
Disabling the entire cache control headers is not a recommended approach and we should avoid it
2. Customize Cache Control Headers
Most times, we don’t want to disable the Spring security cache control headers but may want to customize these cache control headers per action by overriding them using the HttpServletResponse
.
@GetMapping("/home")
public String home(HttpServletResponse response){
response.setHeader("Cache-Control", "no-transform, public, max-age=86400");
return "index";
}
Summary
In this article, we saw how to control and customize the cache control headers in Spring security. We learned Spring security automatically adds these headers, but it also provides flexibility to customize these cache control headers for our application.