| | |
| | | package com.zy.common.config; |
| | | |
| | | import com.zy.common.constant.MesConstant; |
| | | import com.zy.common.utils.Http; |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | 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.web.cors.CorsConfiguration; |
| | | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
| | | import org.springframework.web.filter.CorsFilter; |
| | | import org.springframework.web.servlet.AsyncHandlerInterceptor; |
| | | import org.springframework.web.servlet.config.annotation.CorsRegistry; |
| | | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; |
| | | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; |
| | | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import javax.servlet.http.HttpServletResponse; |
| | | |
| | | /** |
| | | * Created by vincent on 2019-06-13 |
| | |
| | | public void addInterceptors(InterceptorRegistry registry) { |
| | | registry.addInterceptor(adminInterceptor) |
| | | .addPathPatterns("/**") |
| | | ; |
| | | ; |
| | | } |
| | | |
| | | @Override |
| | | public void addCorsMappings(CorsRegistry registry) { |
| | | registry.addMapping("/**") |
| | | .allowedOrigins("*") // 使用 allowedOriginPatterns 而不是 allowedOrigins |
| | | .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") |
| | | .allowedHeaders("*") |
| | | .allowCredentials(true) |
| | | .maxAge(3600); |
| | | } |
| | | |
| | | /** |
| | | * 方式二:使用 Filter(更全面,优先级更高) |
| | | */ |
| | | @Bean |
| | | public FilterRegistrationBean<CorsFilter> corsFilter() { |
| | | CorsConfiguration config = new CorsConfiguration(); |
| | | |
| | | // 允许所有域名 |
| | | config.addAllowedOrigin("*"); |
| | | |
| | | // 允许任何头 |
| | | config.addAllowedHeader("*"); |
| | | |
| | | // 允许任何方法(GET, POST, PUT, DELETE, OPTIONS等) |
| | | config.addAllowedMethod("*"); |
| | | |
| | | // 允许凭证(如果需要cookie等凭证,设置为true,但需要指定具体域名) |
| | | config.setAllowCredentials(false); |
| | | |
| | | // 预检请求的有效期,单位为秒 |
| | | config.setMaxAge(3600L); |
| | | |
| | | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); |
| | | source.registerCorsConfiguration("/**", config); |
| | | |
| | | FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source)); |
| | | |
| | | // 设置优先级最高 |
| | | bean.setOrder(Ordered.HIGHEST_PRECEDENCE); |
| | | |
| | | return bean; |
| | | } |
| | | |
| | | |
| | | } |