package com.mortals.xhx.base.framework.config;

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;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author: zxfei
 * @date: 2022/2/15 13:16
 * @description:
 **/
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Bean
    public CorsFilter corsFilter(){
        //初始化配置对象
        CorsConfiguration configuration = new CorsConfiguration();
        //允许跨域访问的域名
        configuration.addAllowedOrigin("*");
        // configuration.setAllowCredentials(true);  //运行携带cookie
        configuration.addAllowedMethod("*"); //代表所有请求方法
        configuration.addAllowedHeader("*"); //允许携带任何头信息

        //初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource=new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",configuration);

        //返回CorSfilter实例，参数
        return new CorsFilter(configurationSource);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedMethods(new String[] { "GET", "POST","PUT","DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}
