前三种方法参考:spring boot 跨域

4、Spring Security解决方案

如果项目中使用了Spring Security 那么关于Spring Boot的跨域配置会全部失效
因为请求被 Spring Security 拦截了。

当引入了 Spring Security 的时候,我们有两种办法开启 Spring Security 对跨域的支持。

1、添加CORS支持

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.authorizeRequests()
  6. .anyRequest().authenticated()
  7. .and()
  8. .formLogin()
  9. .permitAll()
  10. .and()
  11. .httpBasic()
  12. .and()
  13. .and()
  14. .csrf()
  15. .disable();
  16. http.cors();
  17. }
  18. }

一个 .cors 就开启了 Spring Security 对 CORS 的支持。

2、spring security全局配置

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.authorizeRequests()
  6. .anyRequest().authenticated()
  7. .and()
  8. .formLogin()
  9. .permitAll()
  10. .and()
  11. .httpBasic()
  12. .and()
  13. .and()
  14. .csrf()
  15. .disable();
  16. http.cors().configurationSource(corsConfigurationSource())
  17. }
  18. @Bean
  19. CorsConfigurationSource corsConfigurationSource() {
  20. CorsConfiguration configuration = new CorsConfiguration();
  21. configuration.addAllowedOrigin("*");
  22. configuration.addAllowedMethod("*");
  23. configuration.addAllowedHeader("*");
  24. configuration.setAllowCredentials(true);
  25. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  26. source.registerCorsConfiguration("/**", configuration);
  27. return source;
  28. }
  29. }

通过 CorsConfigurationSource 实例对跨域信息作出详细配置,
例如允许的请求来源、允许的请求方法、允许通过的请求头、探测请求的有效期、需要处理的路径等等。

5、OAuth2跨域

还有一种情况就是 OAuth2 允许跨域,如果用户要访问 OAuth2 端点,
例如 /oauth/token ,出现了跨域该怎么配置呢?
主要是配置一个 CorsFilter,参考【1.2.过滤器预处理(SpringMVC)】

@Configuration
public class GlobalCorsConfiguration {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

然后在 SecurityConfig 中开启跨域支持:

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...
    ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/**")
                .and()
                .csrf().disable().formLogin()
                .and()
                .cors();
    }
}