package com.sysu.admin.support.cfg;

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;

/**
 * @title CorsCfg.java
 * @description 跨域设置 （@CrossOrigin(origins = "*", allowedHeaders = "*",methods = {RequestMethod.GET,
 *              RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH,
 *              RequestMethod.DELETE, RequestMethod.OPTIONS, RequestMethod.TRACE})）
 * @author Sixian.xie
 * @date 2020年6月18日下午5:44:02
 */
@Configuration
public class CorsConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1 设置访问源地址
        corsConfiguration.addAllowedOrigin("*");
        // 2 设置访问源请求头
        corsConfiguration.addAllowedHeader("*");
        // 3 设置访问源请求方法
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 4 对接口配置跨域设置
        source.registerCorsConfiguration("/site/**", buildConfig());
        source.registerCorsConfiguration("/api/**", buildConfig());
        source.registerCorsConfiguration("/WEB-INF/static/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
