【发布时间】:2019-05-28 18:10:55
【问题描述】:
我有一个 CORS 配置:
@Bean
CorsConfigurationSource corsConfigurationSource() {
LOGGER.info("Configuring CORS");
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000", "https://localhost:3000", "http://localhost:2199", "https://localhost:2199"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(
Arrays.asList("Access-Control-Allow-Headers",
"Access-Control-Allow-Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers", "Origin", "Cache-Control",
"Content-Type", "Authorization", "Accept"));
configuration.setAllowedMethods(
Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
这适用于这个请求:
curl -v -XOPTIONS -H 'Access-Control-Request-Headers: content-type' -H 'Origin: http://localhost:3001' http://localhost:8080/auth/create-account
它返回200
如果我添加Access-Control-Request-Method: POST它不起作用
curl -v -XOPTIONS -H 'Access-Control-Request-Headers: content-type' -H 'Origin: http://localhost:3001' http://localhost:8080/auth/create-account -H 'Access-Control-Request-Method: POST'
这里是控制器:
@RestController
@RequestMapping("/auth")
public class AuthEndpoint {
@PostMapping("/login")
public ResponseEntity<Object> doLogin(@RequestBody @Valid LoginDTO loginDTO) {
LOGGER.debug("Attempting login {}", loginDTO);
try {
.....
春天的日志说:
2019-01-01 21:16:35.100 DEBUG 24848 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : OPTIONS "/auth/create-account", parameters={}
2019-01-01 21:16:35.104 DEBUG 24848 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<java.lang.Object> rest.AuthEndpoint.createAccount(NewAccountDTO)
2019-01-01 21:16:35.106 DEBUG 24848 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2019-01-01 21:16:35.112 DEBUG 24848 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2019-01-01 21:16:35.112 DEBUG 24848 --- [nio-8080-exec-1] o.s.orm.jpa.EntityManagerFactoryUtils : Closing JPA EntityManager
2019-01-01 21:16:35.112 DEBUG 24848 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 403 FORBIDDEN
看起来调度程序 servlet 正在拦截并杀死它,但只有 Access-Control-Request-Method 标头,没有该标头它可以工作。
现在,如果我更改控制器以添加此:@CrossOrigin(origins = "http://localhost:3000") 两种方式都可以。
我的问题是如何全局配置我的整个应用程序以避免必须使用(应该是多余的)@CrossOrigin 注释来装饰每个 REST 控制器?
【问题讨论】:
-
你没看过这个 - Global CORS Configuration 吗?
-
在 setAllowedMethod 数组列表中添加“OPTION”。
标签: spring spring-boot cors spring-web