package com.template.core;

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;

@Configuration
public class CORSConfiguration{
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //设置属性
        //允许跨域请求的地址，*表示所以
//      corsConfiguration.addAllowedOrigin("*");//注意：这个注释，换成下面一行的代码
        corsConfiguration.addAllowedOriginPattern("*");
        //跨域的请求头
        corsConfiguration.addAllowedHeader("*");
        //跨域的请求方法
        corsConfiguration.addAllowedMethod("*");
        //在跨域请求的时候使用同一个Session
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
