在我的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'");
}
有谁知道如何正确地做到这一点?
你根本不需要调用 .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'");
}