Gateway解决跨域问题

33 阅读1分钟

 说明

正常学习测试无需CusGatewayProperties类,该类只是实现可以在yml中配置的功能,直接将CusGatewayConfiguration中的相关属性替换成yml中想配置的值即可

CusGatewayProperties

@Component
@ConfigurationProperties(value = "cus.gateway")
public class CusGatewayProperties {
    private List<String> allowedOriginPatterns;
    private List<String> allowedHeaders;
    private List<String> allowedMethods;

    public List<String> getAllowedOriginPatterns() {
        return allowedOriginPatterns;
    }

    public void setAllowedOriginPatterns(List<String> allowedOriginPatterns) {
        this.allowedOriginPatterns = allowedOriginPatterns;
    }

    public List<String> getAllowedHeaders() {
        return allowedHeaders;
    }

    public void setAllowedHeaders(List<String> allowedHeaders) {
        this.allowedHeaders = allowedHeaders;
    }

    public List<String> getAllowedMethods() {
        return allowedMethods;
    }

    public void setAllowedMethods(List<String> allowedMethods) {
        this.allowedMethods = allowedMethods;
    }
}

CusGatewayConfiguration

@Configuration
public class CusGatewayConfiguration {

    @Resource
    private CusGatewayProperties cusGatewayProperties;

    /**
     * 处理跨域问题
     *
     * @return corsWebFilter
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        //请求来源
        Optional.ofNullable(cusGatewayProperties.getAllowedOriginPatterns()).orElse(new ArrayList<>())
                .forEach(config::addAllowedOriginPattern);
        //请求头
        Optional.ofNullable(cusGatewayProperties.getAllowedHeaders()).orElse(new ArrayList<>())
                .forEach(config::addAllowedHeader);
        //请求方法
        Optional.ofNullable(cusGatewayProperties.getAllowedMethods()).orElse(new ArrayList<>())
                .forEach(config::addAllowedMethod);
        //允许携带cookie
        config.setAllowCredentials(true);
        configSource.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(configSource);
    }
}

application.yml

cus:
  gateway:
    allowed-origin-patterns: '*'

Postman跨域模拟

添加Origin请求头,设定跨域地址,如果响应中有Access-Control-Allow-Origin则说明允许跨域。

否则不允许

问题排查

如果配置后仍不允许跨域,可以在org.springframework.web.cors.reactive.DefaultCorsProcessor#process处debug排查, 实际的跨域校验逻辑在org.springframework.web.cors.reactive.DefaultCorsProcessor#handleInternal中

参考资料

[1].gateway项目