package com.infoepoch.pms.dispatchassistant.common.configuration;


import com.infoepoch.pms.dispatchassistant.common.utils.ListTool;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @program: scm
 * @description: CorsConfig(CORS)过滤
 * @author: zhangyd
 * @create: 2020-03-04 15:54
 **/
@Configuration
public class CorsConfig {


    /**
     * 跨域拦截过滤器
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        // 不根据origin拦截
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        // 不根据method拦截
        String allowedMethods = "*";
        config.setAllowedMethods(ListTool.splitString(allowedMethods, ","));
        // 不根据header拦截
        String allowedHeaders = "*";
        config.setAllowedHeaders(ListTool.splitString(allowedHeaders, ","));
        // 设置过滤器匹配uri，/**表示匹配所有地址
        configSource.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(configSource));
        // 这个顺序很重要哦，为避免麻烦请设置在最前
        bean.setOrder(0);
        return bean;
    }
}


