SpringSecurity配置排坑

669 阅读1分钟

SpringSecurity启用iframe支持

在某次升级后,其他组反馈无法在iframe中访问服务。

Refused to display 'xxx.com' in a frame because it set 'X-Frame-Options' to 'deny'

image-20220921191701334

经过排查,原因是引入Spring OAuth2的时候,引入了SpringSecurity,而SpringSecurity为了安全,默认禁用了iframe,所以需要手动开启。

@Configuration
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE) // 需要配置这个,不然配置可能会不生效
public class SecurityConfig extends WebSecurityConfigurerAdapter {
​
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable() // 由于API通常部署在反向代理后面,CORS检查没有意义
                .cors().disable();
​
        // 通常为了高可用部署会禁用spring的session生成,采用cookie验证的方案。
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
​
        http
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").permitAll();
​
        // 启用iframe支持
        http.headers().frameOptions().disable();
    }
​
}

SpringSecurity修改默认防火墙

The request was rejected because the URL contained a potentially malicious String "//"

Image

因为SpringSecurity默认的防火墙是严格模式StrictHttpFirewall,会默认禁止URL路径出现不安全的字符,所以需要修改为DefaultHttpFirewall image-20220921191951305

@Bean
HttpFirewall httpFirewall() {
    return new DefaultHttpFirewall();
}

SpringSecurity配置未生效

修改了http.headers().frameOptions().disable();,但是第一次响应头里面还是有X-Frame-Options: DENY,原因是配置未生效,需要将SecurityConfig的配置优先级提高

@Configuration
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE) // 需要配置这个,不然配置可能会不生效
public class SecurityConfig extends WebSecurityConfigurerAdapter {
​
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
    }
​
}

参考