简体   繁体   中英

How to close connection with netty CorsHandler

How do you make netty's CorsHandler close its connection? It closes by default when the origin passes but it does not close when the origin is not allowed. I setup a server like this with the CorsHandler instance.

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.codec.http.cors.CorsHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Runs netty with a CORS handler on 8080
 */
public class NettyCorsApp {
    private static final int PORT = 8080;

    public static void main(String[] args) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(eventLoopGroup)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(1024 * 1024)); // 1MB
                            pipeline.addLast(new CorsHandler(
                                    CorsConfigBuilder.forOrigin("http://example.com")
                                            .allowedRequestMethods(HttpMethod.POST)
                                            .build())
                            );
                        }
                    })
                    .channel(NioServerSocketChannel.class);
            Channel channel = bootstrap.bind(PORT).sync().channel();
            channel.closeFuture().sync();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}

When you request from an origin that passes the CORS check, the CorsHandler closes the connection like you would expect.

$ curl -sv -X OPTIONS -H 'Origin: http://example.com' -H 'Access-Control-Request-Method: POST' http://localhost:8080
* Rebuilt URL to: http://localhost:8080/
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> OPTIONS / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Origin: http://example.com
> Access-Control-Request-Method: POST
>
< HTTP/1.1 200 OK
< access-control-allow-origin: http://example.com
< vary: origin
< access-control-allow-methods: POST
< access-control-allow-headers:
< access-control-max-age: 0
< date: "Tue, 26 Sep 2017 20:03:53 GMT"
< content-length: 0
<
* Connection #0 to host localhost left intact

But when you request from an origin that does not pass the CORS check, it does not close the connection.

$ curl -sv -X OPTIONS -H 'Origin: http://invalid.com' -H 'Access-Control-Request-Method: POST' http://localhost:8080
* Rebuilt URL to: http://localhost:8080/
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> OPTIONS / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Origin: http://invalid.com
> Access-Control-Request-Method: POST
>
< HTTP/1.1 200 OK
* no chunk, no close, no size. Assume close to signal end
<

This may be a bug in netty, if so I will submit it there.

Following what @Ferrybig pointed out, CorsHandler is not closing the connection intentionally because there is no Connection: close header in the request. Http 1.0 assumes the tcp connection should be closed by default and http 1.1 (which curl defafdults to) should stay open by default.

The reason curl did not exit on a bad origin is because CorsHandler did not include a Content-Length header in its response, which is a bug.

https://github.com/netty/netty/pull/7261

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM