【发布时间】:2014-09-26 14:24:53
【问题描述】:
我希望为一些静态资源(例如图像)启用 HTTP 缓存,这些资源的访问受到 Spring Security 的限制。 (这些资源不是安全关键,但也不应该公开访问)。如何避免让 Spring Security 添加禁用缓存的 HTTP 响应标头?
如果我将setCachePeriod() 添加到WebMvcConfigurerAdapter.addResourceHandlers() 中的资源处理程序注册中,如下所示:
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/").setCachePeriod(3600);
返回的资源仍然带有以下禁用缓存的标头:
Cache-Control: max-age=3600, must-revalidate
Expires: Mon, 04 Aug 2014 07:45:36 GMT
Pragma: no-cache
我想避免在项目中引入任何 XML 配置,目前只使用 Java 注解配置。
有没有比扩展 Spring 资源处理程序更好的解决方案?
【问题讨论】:
-
即使覆盖/实现资源处理程序也无济于事。 Spring Security 默认禁用安全资源的缓存。如果您不希望禁用这些资源的缓存。这可以使用
HttpSecurity来完成,http.antMatcher("/static/**").headers().disable()会禁用 Spring Security 设置的所有标头。这也在 Spring Security 参考指南中的 here 中进行了解释。 -
谢谢 M. Deinum。另一个问题是配置已经有一个
antMatchers()调用,如下所示:http.authorizeRequests().antMatchers("/login", "/static/public/**").permitAll().anyRequest().authenticated()。如何在不覆盖上述antMatchers()规则的情况下将headers().disable()规则应用于“/static/**”? -
没关系,添加另一个或使用
and()链接多个配置。类似authenticated().and().headers().disabled()。 -
我想禁用“/static/**”的 Spring Security 标头。我了解您的建议会为所有请求或与现有
antMatchers()规则匹配的请求禁用它们。 -
不...您的理解不正确...您也可以随时添加一个额外的
antMatcher元素。它们都合并在一起了。
标签: java spring spring-mvc caching spring-security