Spring Cloud Gateway and CORS header



我正在尝试使用org.springframework.cloud.gateway.mvc.ProxyExchange代理转发请求。通话正常。

在我的场景中,我喜欢将它与浏览器调用集成,但是得到一个CORS-header问题。

(1)控制器内源:

@RequestMapping(value = "/public**", method = RequestMethod.GET)
public ResponseEntity<byte[]> forwardHttpRequestForGet(
HttpServletRequest httpServletRequest,
@RequestParam MultiValueMap<String, String> requestParams,
@RequestHeader HttpHeaders requestHeaders,
ProxyExchange<byte[]> proxy) throws Exception {

ResponseEntity<byte[]> responseEntity = cloudGatewayService.proxyForwardToApplication(httpServletRequest, requestParams,requestHeaders, proxy);
return responseEntity;
}

(2)使用的CloudGatewayService来源:

public ResponseEntity<byte[]> proxyForwardToApplication(
HttpServletRequest httpServletRequest,
MultiValueMap<String, String> requestParams,
HttpHeaders requestHeaders, ProxyExchange<byte[]> proxy) throws Exception {

String authorizationHeader = httpServletRequest.getHeader(AUTHORIZATION_HEADER);
String forwardUrl = "newUrl"

return proxy.sensitive("cookie")
.headers(requestHeaders)
.uri(forwardUrl).get();
}

如何为Spring Cloud Gateway添加CORS支持?

没有云MVC特有的。即使它是一个代理,我们也必须在web应用程序中添加CORS支持。

因为它是一个spring引导项目,所以我在这里也添加了spring安全性。添加了一个可以填充标题的过滤器。

注意:添加所需的标题为您的选项调用(preflight),还支持相应的GET,POST, DELETE等调用。

响应头可以添加到http响应