内容安全策略 Spring Security

新手上路,请多包涵

假设一个 spring security 和 spring mvc 的工作 hello world 示例。

当我使用 wireshark 进行跟踪时,我在 http 请求中看到以下标志

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
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; Path=/; Secure; HttpOnly

我想将此添加到我的标题中:

 Content-Security-Policy: script-src 'self'

我知道 X-Frame-Options 的作用几乎相同,但它仍然让我睡得更好。现在我想我需要在我的 spring 安全配置的配置功能下完成它但是我不知道具体如何,即我想 .headers().something.something(self)

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
//          .csrf().disable()
//          .headers().disable()
            .authorizeRequests()
                .antMatchers(   "/register",
                                "/static/**",
                                "/h2/**",
                                "/resources/**",
                            "/resources/static/css/**",
                                "/resources/static/img/**" ,
                                "/resources/static/js/**",
                                "/resources/static/pdf/**"
                                ).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

原文由 Tito 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 726
2 个回答

只需像这样使用 addHeaderWriter 方法:

 @EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // ...
      .headers()
        .addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
      // ...
  }
}

请注意,一旦您指定了任何应该包含的标头,那么只会包含那些标头。

要包含默认标头,您可以执行以下操作:

 http
  .headers()
    .contentTypeOptions()
    .xssProtection()
    .cacheControl()
    .httpStrictTransportSecurity()
    .frameOptions()
    .addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
    // ...

可以参考 spring security文档

原文由 Christopher Pelloux 发布,翻译遵循 CC BY-SA 3.0 许可协议

虽然 StaticHeadersWriter 的方法有效,但在最新版本的 Spring Security 中,可以使用特殊方法:

 headers()
    .contentSecurityPolicy("script-src 'self'");

有关详细信息,请参阅文档: https ://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/headers.html#headers-csp-configure

原文由 Slava Semushin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题