Cache control is a set of HTTP headers sent by the server to control how the user's browser is allowed to cache resources.
In the previous chapter, we have seen that Spring Security automatically disables caching for secured resources.
If we want to benefit from cache control, we must first disable that feature:
security.headers.cache=false # Cache resources for 3 days spring.resources.cache-period=259200
Now, launch the application, go to the main page, and check the Chrome developer console. You will see that our JavaScript files are Gzipped and cached, as marked in the following screenshot:
If you want more control over your cache, you could add handlers for your own resources in your configuration:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // This is just an example registry.addResourceHandler("/img/**") .addResourceLocations("classpath:/static/images/") .setCachePeriod(12); }
We could also override the Spring Security default settings. If we want to deactivate the "no cache control" policy for our API, we can change the ApiSecurityConfiguration
class like this:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
// This is just an example – not required in our case
.headers().cacheControl().disable()
.httpBasic().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET).hasRole("USER")
.antMatchers(HttpMethod.POST).hasRole("ADMIN")
.antMatchers(HttpMethod.PUT).hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE).hasRole("ADMIN")
.anyRequest().authenticated();
}