CORS跨域

178 阅读1分钟

方式1


@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
        http.formLogin();
        http.cors().and().csrf().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        //设置允许被哪些origin访问,或者直接配置*,表示允许所有站点跨域访问
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8081"));
        
        //设置允许被哪些方法访问,或者直接配置*,表示允许所有方法访问
        configuration.setAllowedMethods(Arrays.asList("GET"));
        
        //true表示浏览器可以发送cookie,但js需要设置withCredentials = true,否则也不会发送cookie给服务器
        //true时setAllowedOrigins不能设置为*,必须指定具体的origin
        configuration.setAllowCredentials(false);
        
        //设置允许暴露给前端的请求头,或者设置为*,表示允许暴露所有请求头(只有这里配置了,前端才可以获取到对应的header)
        configuration.setExposedHeaders(Arrays.asList("X-Another-Custom-Header"));
        
        //设置允许前端添加的header,或者设置为*,表示允许设置所有的
        //前端只允许添加后端允许的header,否则会CORS,但后端设置后,前端可以不添加
        configuration.addAllowedHeader("X-Another-Custom-Header");
        configuration.addAllowedHeader("X-My-Custom-Header");
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    ```

# 方式2

* * *

```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("http://localhost:8081")
        .allowedMethods("*")
        .allowedHeaders("*");
    }
}

在 Spring Boot 中,还可以通过全局配置一次性解决这个问题,全局配置只需要在 SpringMVC 的配置类中重写 addCorsMappings 方法即可

方式3


@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);
    }
}

主要针对OAuth2 允许跨域。