package com.app.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 功能描述：
 * todo ??? 结合Security之后，还需要在SecurityConfig中设置`and().cors().and().csrf().disable()`
 * @Author 梁展鹏
 */
@Configuration
public class CorcConfig {

    private CorsConfiguration buildConfig() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*"); // 设置允许跨域请求的域名
        config.addAllowedHeader("*"); //允许任何请求头
        config.addAllowedMethod("*"); //允许任何方法（post、get等）
        config.setAllowCredentials(Boolean.TRUE); // 是否允许证书，不再默认开启
        config.addExposedHeader(HttpHeaders.SET_COOKIE);
        config.addExposedHeader(HttpHeaders.AUTHORIZATION); // 如果不设置这个属性前端无法通过response header获取到Authorization也就是token
        config.setMaxAge(60 * 60L); //maxAge(3600)表明在3600秒内，不需要再发送预检验请求，可以缓存该结果
        return config;
    }

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

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

}
