user3742622 user3742622 - 5 months ago 383
Java Question

Java + Spring Boot: I am trying to add CacheControl header to ResponseEntity

I am not so good in Java + Spring, but I'd like to add

Cache-Control
header to my
ResponseEntity
.

@RequestMapping(value = "/data/{id}", method = GET")
public ResponseEntity<String> getData(@PathVariable("id") String id) {
try {
...
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl("max-age=600");

return new ResponseEntity<String>(body, headers, HttpStatus.OK);
}
}


I added two lines of code for
HttpHeaders
and now I get two
Cache-Control
headers in my response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
Cache-Control: max-age=600
Content-Type: application/json;charset=UTF-8
Content-Length: 18223
Date: Wed, 29 Jun 2016 21:56:57 GMT


What did I do wrong? Could somebody give me a helping hand.

Answer

TL;DR

Just add the following to your application.properties:

security.headers.cache=false

More Details

As Spring Security documentation states:

Spring Security allows users to easily inject the default security headers to assist in protecting their application. The default for Spring Security is to include the following headers:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

now I get 2 CacheControl headers in my response

One of them is provided by Spring Security. If you don't like them, you can disable the default Cache-Control headers in your WebSecurityConfigurerAdapter:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // Other configurations

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // Other configurations
                .headers()
                    .cacheControl().disable();
    }
}

Since you're using Spring Boot, you can achieve the same using the security.headers.* properties. In order to disable those default Cache-Control header, just add the following to your application.properties:

security.headers.cache=false

Also, more idiomatic way of adding Cache-Control headers is to use the new cacheControl builder:

ResponseEntity.ok()
              .cacheControl(CacheControl.maxAge(600, TimeUnit.SECONDS))
              .body(body);