【问题标题】:Java + Spring Boot: I am trying to add CacheControl header to ResponseEntityJava + Spring Boot:我正在尝试将 CacheControl 标头添加到 ResponseEntity
【发布时间】:2016-11-03 01:23:25
【问题描述】:

我不太擅长 Java + Spring,但我想将 Cache-Control 标头添加到我的 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);
        }
}

我为HttpHeaders 添加了两行代码,现在我的响应中有两个Cache-Control 标头:

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

我做错了什么?

【问题讨论】:

  • 你在使用 Spring Security 吗?
  • 是的,我的应用具有访问 REST API 的基本身份验证。

标签: java spring spring-mvc spring-security spring-boot


【解决方案1】:

TL;DR

只需将以下内容添加到您的application.properties

security.headers.cache=false

更多详情

正如Spring Security documentation 所说:

Spring Security 允许用户轻松注入默认安全性 标头以帮助保护其应用程序。默认为 Spring Security 将包含以下标头:

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

现在我的响应中有 2 个 CacheControl 标头

其中一个由 Spring Security 提供。如果您不喜欢它们,可以禁用 WebSecurityConfigurerAdapter 中的默认 Cache-Control 标头:

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

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

由于您使用的是 Spring Boot,因此您可以使用 security.headers.* 属性实现相同的目的。要禁用默认的Cache-Control 标头,只需将以下内容添加到您的application.properties

security.headers.cache=false

另外,添加Cache-Control 标头的更惯用方法是使用新的cacheControl 构建器:

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

【讨论】:

  • 太棒了,这对我也有用。出于某种原因,security.headers.cache=false 并没有影响结果,但是显式扩展 WebSecurityConfigurerAdapter 就可以了。现在我让我的控制器明确声明他们的缓存策略。很好的提示。
猜你喜欢
  • 2022-07-25
  • 2022-01-13
  • 2018-04-04
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 2018-03-14
  • 2016-01-17
  • 2020-02-09
相关资源
最近更新 更多