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

问题描述 投票:0回答:1

在我的javaspring-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();
    }
}

我需要配置一个 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'");
    }

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

spring spring-boot http spring-security content-security-policy
1个回答
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'");
    }

© www.soinside.com 2019 - 2024. All rights reserved.