Spring Cloud Gateway CORS

Java

Kotlin

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
@Configuration
class RouteConfiguration {

@Bean
fun allowCORS(): WebFilter {
return WebFilter { webExchange, chains ->
val request = webExchange.request
val requestHeaders = request.headers
val response = webExchange.response
val respHeaders = response.headers

respHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
respHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "*")
respHeaders.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE)
respHeaders.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.accessControlRequestHeaders)
respHeaders.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*")
respHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")

if (request.method == HttpMethod.OPTIONS) {
response.statusCode = HttpStatus.OK
Mono.empty()
} else {
chains.filter(webExchange)
}
}
}

companion object {
const val MAX_AGE = "18000L"
}
}

Refer

http://springcloud.cn/view/343