package com.huimv.gateway.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.DefaultCorsProcessor; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.util.pattern.PathPatternParser; import java.util.Collections; /** * @Project : huimv.shiwan * @Package : com.huimv.gateway.config * @Description : TODO * @Author : yuxuexuan * @Create : 2021/4/28 0028 15:45 **/ @Configuration public class GatewayCrosConfig { // @Bean // public CorsWebFilter corsWebFilter(){ // // UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // CorsConfiguration corsConfiguration = new CorsConfiguration(); // //1.配置跨域 // corsConfiguration.addAllowedHeader("*"); // corsConfiguration.addAllowedMethod("*"); //// corsConfiguration.addAllowedOrigin("*"); // corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*")); // corsConfiguration.setAllowCredentials(true); // // // source.registerCorsConfiguration("/**",corsConfiguration); // return new CorsWebFilter(source); // } @Bean public CorsResponseHeaderFilter corsResponseHeaderFilter() { return new CorsResponseHeaderFilter(); } @Bean public CorsWebFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", buildCorsConfiguration()); CorsWebFilter corsWebFilter = new CorsWebFilter(source, new DefaultCorsProcessor() { @Override protected boolean handleInternal(ServerWebExchange exchange, CorsConfiguration config, boolean preFlightRequest) { // 预留扩展点 // if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) { return super.handleInternal(exchange, config, preFlightRequest); // } // return true; } }); return corsWebFilter; } private CorsConfiguration buildCorsConfiguration() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*")); //corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS); corsConfiguration.addAllowedMethod(HttpMethod.POST); corsConfiguration.addAllowedMethod(HttpMethod.GET); corsConfiguration.addAllowedMethod(HttpMethod.PUT); corsConfiguration.addAllowedMethod(HttpMethod.DELETE); corsConfiguration.addAllowedMethod(HttpMethod.PATCH); // corsConfiguration.addAllowedMethod("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.setMaxAge(7200L); corsConfiguration.setAllowCredentials(true); return corsConfiguration; } }