首页 > 解决方案 > 扩展 WebSecurityConfigurerAdapter 不添加 CSP 标头

问题描述

在我的 Spring MVC (5.0.3) 应用程序中,我添加了一个SecurityConfig扩展WebSecurityConfigurerAdapter如下的类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter 
{

    @Override
    protected void configure(HttpSecurity http) throws Exception 
    {
        http.headers().contentSecurityPolicy("script-src 'self'");
    }
    
}

我的期望是在浏览 http://localhost:2020/webapp/ 之后,我会在浏览器的开发者控制台(网络选项卡)中看到 CSP 标头。但是,与 CSP 相关的任何内容都不会添加到响应标头中。

我已经通过在行上应用断点进行检查,http.headers().contentSecurityPolicy("script-src 'self'");并且它在上下文加载期间命中了一次。

为什么没有在响应中添加 CSP 标头有什么问题?

更新:我什至尝试使用http.headers(),根据文档,这个调用没有其他方法,将添加默认安全标头。但就我而言,没有添加任何默认安全标头。

根据要求,我已经上传了最小的、可复制的示例@Google Drive,单击此处下载

标签: javaspring-mvcspring-security

解决方案


Looked at the mvce and it appears you are not registering the spring security filter chain. Add below in web.xml and it should all work.

<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

推荐阅读