@@ -34,26 +34,30 @@ class CorsMiddleware(
3434 override fun invoke (context : RequestContext , response : FullHttpResponse ): FullHttpResponse {
3535 val httpHeaders = response.headers()
3636 val requestOrigin = context.headers[HttpHeaderNames .ORIGIN ]
37-
38- if (allowedOrigins.contains(" *" )) {
39- httpHeaders[HttpHeaderNames .ACCESS_CONTROL_ALLOW_ORIGIN ] = " *"
37+ val allowedOrigin = if (allowedOrigins.contains(" *" )) {
38+ " *"
4039 } else if (requestOrigin != null ) {
41- try {
42- val uri = URI (requestOrigin)
43- val host = uri.host
44- if (allowedOrigins.contains(host) || allowedOrigins.contains(requestOrigin)) {
45- httpHeaders[HttpHeaderNames .ACCESS_CONTROL_ALLOW_ORIGIN ] = requestOrigin
46- } else {
47- httpHeaders[HttpHeaderNames .ACCESS_CONTROL_ALLOW_ORIGIN ] = " null"
48- }
49- } catch (e: URISyntaxException ) {
50- httpHeaders[HttpHeaderNames .ACCESS_CONTROL_ALLOW_ORIGIN ] = " null"
40+ val host = try {
41+ URI (requestOrigin).host
42+ } catch (e: Exception ) {
5143 logger.error(" Invalid Origin header: $requestOrigin " , e)
44+ null
45+ }
46+
47+ if (host != null && allowedOrigins.contains(host) || allowedOrigins.contains(requestOrigin)) {
48+ requestOrigin
49+ } else {
50+ null
5251 }
5352 } else {
54- httpHeaders[ HttpHeaderNames . ACCESS_CONTROL_ALLOW_ORIGIN ] = " null"
53+ null
5554 }
5655
56+ if (allowedOrigin == null ) {
57+ logger.debug(" CORS origin not allowed: $requestOrigin " )
58+ return response
59+ }
60+ httpHeaders[HttpHeaderNames .ACCESS_CONTROL_ALLOW_ORIGIN ] = allowedOrigin
5761 httpHeaders[HttpHeaderNames .ACCESS_CONTROL_ALLOW_METHODS ] = allowedMethods.joinToString(" , " )
5862 httpHeaders[HttpHeaderNames .ACCESS_CONTROL_ALLOW_HEADERS ] = allowedHeaders.joinToString(" , " )
5963 return response
0 commit comments