Spring安全响应头

时间:2018-07-26 14:28:02

标签: java spring-mvc spring-security swagger

我正在使用Spring MVC创建具有常用REST方法(GET,POST,PUT,DELETE)的API,现在我需要像这样配置响应头:

{
  "cache-control": "no-cache, no-store, max-age=0, must-revalidate",
  "content-type": "application/json;charset=UTF-8",
  "date": "Thu, 26 Jul 2018 14:19:08 GMT",
  "expires": "0",
  "pragma": "no-cache",
  "strict-transport-security": "max-age=31536000 ; includeSubDomains",
  "transfer-encoding": "chunked",
  "x-content-type-options": "nosniff",
  "x-frame-options": "SAMEORIGIN",
  "x-xss-protection": "1; mode=block"
}

我有这个HttpSecurityConfig类,它具有以下配置:

   @Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable()
            .requiresChannel().anyRequest().requiresSecure()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .securityContext().securityContextRepository(null)
            .and()
            .headers().xssProtection().and()
            .and()
            .headers().frameOptions().sameOrigin()
            .and()
            .headers().cacheControl();
}

由于某种原因,我的POST请求返回了我想要的标头,但是对于GET,PUT和DELETE,某些配置不起作用。当我执行此类请求时,我的标头会像这样返回:

{
  "cache-control": "private",
  "content-type": "application/json;charset=UTF-8",
  "date": "Thu, 26 Jul 2018 14:24:36 GMT",
  "expires": "Thu, 01 Jan 1970 00:00:00 UTC",
  "strict-transport-security": "max-age=31536000 ; includeSubDomains",
  "transfer-encoding": "chunked",
  "x-content-type-options": "nosniff",
  "x-frame-options": "SAMEORIGIN",
  "x-xss-protection": "1; mode=block"
}

有人知道为什么会这样吗?谢谢。

编辑:

我找到了一种“绕过” GET,PUT和DELETE发生情况的方法。 我在HttpSecurityConfig类中添加了以下代码:

            .and()
            .addHeaderWriter((httpServletRequest, httpServletResponse) -> {
                httpServletResponse.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
                httpServletResponse.setHeader("Expires", "0");
                httpServletResponse.setHeader("pragma", "no-cache");
            });

现在,如果响应中包含这些标头,则它们将被覆盖。 如果没有,则会添加它们。

0 个答案:

没有答案