package com.zzsn.modules.filter;

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;


/**
 * 跨域全局处理
 */
//@Configuration
public class CorsConfig {
    //@Bean
    public CorsConfiguration corsConfiguration() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //实际请求中允许携带的首部字段
        corsConfiguration.addAllowedHeader("*");
        //允许那些域跨域访问
        corsConfiguration.addAllowedOrigin("*");
        //允许那些请求方法
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    //@Bean
    public FilterRegistrationBean corsFilter(CorsConfiguration corsConfiguration) {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration); // 4
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

    //@Bean
    //public CorsFilter corsFilter() {
    //    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    //    final CorsConfiguration config = new CorsConfiguration();
    //    config.setAllowCredentials(true);
    //    config.addAllowedOrigin("*");
    //    config.addAllowedHeader("*");
    //    config.addAllowedMethod("*");
    //    config.setAllowCredentials(false);
    //    config.addExposedHeader("*");
    //    //config.addAllowedMethod("OPTIONS");
    //    //config.addAllowedMethod("HEAD");
    //    //config.addAllowedMethod("GET");
    //    //config.addAllowedMethod("PUT");
    //    //config.addAllowedMethod("POST");
    //    //config.addAllowedMethod("DELETE");
    //    //config.addAllowedMethod("PATCH");
    //    source.registerCorsConfiguration("/**", config);
    //    return new CorsFilter(source);
    //}
}
