如何在SecurityConfig类中配置内容安全策略

时间:2020-06-10 08:16:50

标签: spring spring-boot http spring-security content-security-policy

在我的java / spring-boot应用程序中,我具有一个SecurityConfig类,如下所示:

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final BasicAuthenticationProvider basicAuthenticationProvider;

    @Autowired
    public SecurityConfig(BasicAuthenticationProvider basicAuthenticationProvider) {
        this.basicAuthenticationProvider = basicAuthenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher(PATH_NAME)
                .httpBasic()
                .and().authorizeRequests().anyRequest().authenticated()
                .and().csrf().disable();
    }
}

我需要在configure方法中使用代码ContentSecurityPolicy来配置.and().headers().contentSecurityPolicy("script-src 'self'"),但是我尝试了在可能的地方并不断出错(例如无法解析方法.and()尝试以下代码时)

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher(PATH_NAME)
                .httpBasic()
                .and().authorizeRequests().anyRequest().authenticated()
                .and().csrf().disable()
                .and().headers().contentSecurityPolicy("script-src 'self'");
    }

有人知道如何正确地做到这一点吗?

1 个答案:

答案 0 :(得分:0)

您根本不必在.and()之后调用csrf().disable(),因为disable()已经返回了您必须配置的HttpSecurity对象。

类似

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher(PATH_NAME)
                .httpBasic()
                .and().authorizeRequests().anyRequest().authenticated()
                .and().csrf().disable()
                // notice that .and() is removed from the next line
                .headers().contentSecurityPolicy("script-src 'self'");
    }