注入 Filter 解决 Spring Boot 2.x 前后端分离开发 CORS 跨域问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.gioov.nimrodbackend.common;

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.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
* @author godcheese [[email protected]]
* @date 2019-04-03
*/
@Configuration
public class CorsConfiguration {

@Bean
public FilterRegistrationBean<CorsFilter> corsConfig() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
// 是否发送 Cookie
corsConfiguration.setAllowCredentials(true);
// 允许跨域访问的源
corsConfiguration.addAllowedOrigin(org.springframework.web.cors.CorsConfiguration.ALL);
// 允许头部设置
corsConfiguration.addAllowedHeader(org.springframework.web.cors.CorsConfiguration.ALL);
// 允许请求方法
corsConfiguration.addAllowedMethod(org.springframework.web.cors.CorsConfiguration.ALL);
// 预检间隔时间,单位:秒
corsConfiguration.setMaxAge(1800L);
// 允许跨域访问的路径
source.registerCorsConfiguration("/**", corsConfiguration);
// 注入 Filter
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>();
bean.setFilter(new CorsFilter(source));
bean.setName("corsFilter");
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}

}