Created
July 3, 2017 09:12
-
-
Save christoph-daehne/1c2d4342a377b8a21b6a3caedb500e23 to your computer and use it in GitHub Desktop.
Set CORS Headers in Spring Boot Kotlin project with WebFlux and Reactor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.http.HttpMethod | |
import org.springframework.http.HttpStatus | |
import org.springframework.stereotype.Component | |
import org.springframework.web.server.ServerWebExchange | |
import org.springframework.web.server.WebFilter | |
import org.springframework.web.server.WebFilterChain | |
import reactor.core.publisher.Mono | |
@Component | |
class CorsFilter : WebFilter { | |
override fun filter(ctx: ServerWebExchange?, chain: WebFilterChain?): Mono<Void> { | |
if (ctx != null) { | |
ctx.response.headers.add("Access-Control-Allow-Origin", "*") | |
ctx.response.headers.add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS") | |
ctx.response.headers.add("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range") | |
if (ctx.request.method == HttpMethod.OPTIONS) { | |
ctx.response.headers.add("Access-Control-Max-Age", "1728000") | |
ctx.response.statusCode = HttpStatus.NO_CONTENT | |
return Mono.empty() | |
} else { | |
ctx.response.headers.add("Access-Control-Expose-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range") | |
return chain?.filter(ctx) ?: Mono.empty() | |
} | |
} else { | |
return chain?.filter(ctx) ?: Mono.empty() | |
} | |
} | |
} |
Hello Christoph
How can I create unit test to that filter? Have any idea?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Full explanation here https://sandstorm.de/de/blog/post/cors-headers-for-spring-boot-kotlin-webflux-reactor-project.html