第十六章 Security HTTP Response Headers
Spring Security 允许用户注入默认的安全headers,用来保护应用程序。
一、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
也可以使用 Java 来配置响应头的内容:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void config(HttpSecurity http) throws Exception {
http
.headers()
.frameOptions().sameOrigin()
.httpStrictTransportSecurity().disable();
}
}
二、Header 的具体内容
1. Cache Control
缓存控制,意味着用户是否可以通过浏览器缓存来查看经过身份验证的页面。
默认情况下,是不使用缓存的,入股你希望缓存特定的响应,那么可以在应用程序中进行如下配置:
@EnableWeb
public class WebMvcConfiguration impelements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/")
.setCachePeriod(31556926);
}
}
在开发中,我们可以使用 SpringMVC 的 HttpServletResponse 来增加 Header:
@GetMapping("/shops")
public ModelAndView(ModelAndView mv, HttpServletResponse response) {
response.addHeader(HttpHeaders.CACHE_CONTROL, "public,max-age=5");
mv.setViewName("shop");
return mv;
}
2. Content-Type
响应内容的类型
3. Http Strict Transport Security (HSTS)
HTTP 严格传输安全,要求所有请求必须是 https 的。
4. Http Public Key Pinning (HPKP)
防止中间人攻击伪造的证书,它告诉网络客户端将一个特定的加密公钥与一个特定的网络服务器相关联。
5. X-Frame-Options
是否允许网站被添加到一个框架中。如登录到银行的用户可能会点击授予其他用户访问权限的按钮。这种攻击被称为点击劫持。
默认为 DENY。
6. X-XSS-Protection
默认开启,过滤XSS 攻击。
7. Content Security Policy
内容安全策略(CSP)