io.netty.handler.codec.http.cors.CorsConfig Java Examples

The following examples show how to use io.netty.handler.codec.http.cors.CorsConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NettyHttpServerWithCORS.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	String ip = "127.0.0.1";
	int port = 8080;
	ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			
			CorsConfig corsConfig = CorsConfig.withAnyOrigin()
					.allowedRequestHeaders("content-type","accept","MyCustomHeader")
					.allowedRequestMethods(PUT,POST,GET,DELETE)
					.build();
			
			p.addLast(new HttpResponseEncoder());
			p.addLast(new HttpRequestDecoder());
			p.addLast(new HttpObjectAggregator(65536));
			p.addLast(new ChunkedWriteHandler());
			p.addLast(new CorsHandler(corsConfig));
			p.addLast(new SimpleCORSHandler());
		}
	};
	NettyServerUtil.newHttpServerBootstrap(ip, port, channelInit);
}
 
Example #2
Source File: XConfig.java    From xrpc with Apache License 2.0 6 votes vote down vote up
private CorsConfig buildCorsConfig(Config config) {
  if (!config.getBoolean("enable")) {
    return CorsConfigBuilder.forAnyOrigin().disable().build();
  }

  CorsConfigBuilder builder =
      CorsConfigBuilder.forOrigins(getStrings(config, "allowed_origins"))
          .allowedRequestHeaders(getStrings(config, "allowed_headers"))
          .allowedRequestMethods(getHttpMethods(config, "allowed_methods"));
  if (config.getBoolean("allow_credentials")) {
    builder.allowCredentials();
  }
  if (config.getBoolean("short_circuit")) {
    builder.shortCircuit();
  }
  return builder.build();
}
 
Example #3
Source File: HttpStaticFileServerInitializer.java    From codes-scratch-zookeeper-netty with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch)
        throws Exception {
    // Create a default pipeline implementation.
    CorsConfig corsConfig = CorsConfig.withAnyOrigin().build();
    ChannelPipeline pipeline = ch.pipeline();
    // Uncomment the following line if you want HTTPS
    //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
    //engine.setUseClientMode(false);
    //pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(8388608)); // 8MB
    //pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("cors", new CorsHandler(corsConfig));
    pipeline.addLast("handler", new HttpStaticFileServerHandler());
}
 
Example #4
Source File: HttpServerInitHandler.java    From util4j with Apache License 2.0 6 votes vote down vote up
@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline p = ch.pipeline();
		if(sslCtx!=null)
		{
			p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
		}
		p.addLast(new HttpResponseEncoder());//必须放在最前面,如果decoder途中需要回复消息,则decoder前面需要encoder
		p.addLast(new HttpRequestDecoder());
		p.addLast(new HttpObjectAggregator(65536));//限制contentLength
		//大文件传输处理
//		p.addLast(new ChunkedWriteHandler());
//		p.addLast(new HttpContentCompressor());
		//跨域配置
		CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
		p.addLast(new CorsHandler(corsConfig));
		if(unPoolMsg)
		{
			p.addLast(new DefaultListenerHandler<HttpRequest>(new HttpListenerProxy(listener)));
		}else
		{
			p.addLast(new DefaultListenerHandler<HttpRequest>(listener));
		}
	}
 
Example #5
Source File: Http2HandlerTest.java    From xrpc with Apache License 2.0 6 votes vote down vote up
/** Test that onHeadersRead handles requests with no origin header properly. */
@Test
void testOnHeadersRead_noOrigin() {
  CorsConfig corsConfig =
      CorsConfigBuilder.forOrigin("test.domain")
          .allowCredentials()
          .allowedRequestMethods(HttpMethod.GET)
          .build();
  Http2CorsHandler corsHandler = new Http2CorsHandler(corsConfig);

  testHandler = new Http2Handler(mockEncoder, MAX_PAYLOAD, corsHandler);

  headers.method("GET").path(OK_PATH);

  testHandler.onHeadersRead(mockContext, STREAM_ID, headers, 1, true);
  assertEquals(1L, requestMeter.getCount());

  verifyResponse(HttpResponseStatus.OK, ImmutableMap.of(), Optional.empty(), STREAM_ID);
}
 
Example #6
Source File: Http2HandlerTest.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/** Test that OPTIONS request short circuit to preflight response. */
@Test
void testOnHeadersRead_corsShortCircuit() {
  CorsConfig corsConfig = CorsConfigBuilder.forOrigin("test.domain").shortCircuit().build();
  Http2CorsHandler corsHandler = new Http2CorsHandler(corsConfig);

  testHandler = new Http2Handler(mockEncoder, MAX_PAYLOAD, corsHandler);

  headers.method("GET").add("origin", "illegal.domain").path(OK_PATH);

  testHandler.onHeadersRead(mockContext, STREAM_ID, headers, 1, true);
  assertEquals(1L, requestMeter.getCount());

  verifyResponse(HttpResponseStatus.FORBIDDEN, ImmutableMap.of(), Optional.empty(), STREAM_ID);
}
 
Example #7
Source File: AuthConnector.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfig.withAnyOrigin().build();
    ChannelPipeline p = ch.pipeline();
    p.addLast(new HttpResponseEncoder());
    p.addLast(new HttpRequestDecoder());
    p.addLast(new HttpObjectAggregator(65536));
    p.addLast(new ChunkedWriteHandler());
    p.addLast(new CorsHandler(corsConfig));
    p.addLast(new HttpHandler());
}
 
Example #8
Source File: HttpCorsServerInitializer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfig.withAnyOrigin().build();
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new OkResponseHandler());
}
 
Example #9
Source File: Server.java    From qonduit with Apache License 2.0 5 votes vote down vote up
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {

        return new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
                ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                ch.pipeline().addLast("compressor", new HttpContentCompressor());
                ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
                ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
                final Configuration.Cors corsCfg = config.getHttp().getCors();
                final CorsConfigBuilder ccb;
                if (corsCfg.isAllowAnyOrigin()) {
                    ccb = CorsConfigBuilder.forAnyOrigin();
                } else {
                    ccb = CorsConfigBuilder.forOrigins(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
                }
                if (corsCfg.isAllowNullOrigin()) {
                    ccb.allowNullOrigin();
                }
                if (corsCfg.isAllowCredentials()) {
                    ccb.allowCredentials();
                }
                corsCfg.getAllowedMethods().stream().map(HttpMethod::valueOf).forEach(ccb::allowedRequestMethods);
                corsCfg.getAllowedHeaders().forEach(ccb::allowedRequestHeaders);
                CorsConfig cors = ccb.build();
                LOG.trace("Cors configuration: {}", cors);
                ch.pipeline().addLast("cors", new CorsHandler(cors));
                ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
                ch.pipeline().addLast("strict", new StrictTransportHandler(config));
                ch.pipeline().addLast("login", new X509LoginRequestHandler(config));
                ch.pipeline().addLast("doLogin", new BasicAuthLoginRequestHandler(config));
                ch.pipeline().addLast("error", new HttpExceptionHandler());
            }
        };
    }
 
Example #10
Source File: HttpCorsServerInitializer.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new OkResponseHandler());
}
 
Example #11
Source File: IrisNettyCorsConfig.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public CorsConfig build() {
   CorsConfig.Builder builder = allowAny ? CorsConfig.withAnyOrigin()  : CorsConfig.withOrigins(origins);

   return builder
      .allowCredentials()
      .exposeHeaders(exposeRequest)
      .allowedRequestHeaders(allowRequest)
      .allowedRequestMethods(allowMethods)
      .maxAge(1209600)
      .shortCurcuit()
      .build();
}
 
Example #12
Source File: Http2HandlerTest.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/** Test that OPTIONS request short circuit to preflight response. */
@Test
void testOnHeadersRead_preflightOptionsRequest() {
  CorsConfig corsConfig =
      CorsConfigBuilder.forOrigin("test.domain")
          .allowCredentials()
          .allowedRequestMethods(HttpMethod.GET)
          .build();
  Http2CorsHandler corsHandler = new Http2CorsHandler(corsConfig);

  testHandler = new Http2Handler(mockEncoder, MAX_PAYLOAD, corsHandler);

  headers
      .method("OPTIONS")
      .add("origin", "test.domain")
      .add("access-control-request-method", "GET")
      .path(OK_PATH);

  testHandler.onHeadersRead(mockContext, STREAM_ID, headers, 1, true);
  assertEquals(1L, requestMeter.getCount());

  verifyResponse(
      HttpResponseStatus.OK,
      ImmutableMap.of(
          "access-control-allow-methods",
          "GET",
          "access-control-allow-origin",
          corsConfig.origin(),
          "access-control-allow-credentials",
          "true"),
      Optional.empty(),
      STREAM_ID);
}
 
Example #13
Source File: XConfigTest.java    From xrpc with Apache License 2.0 5 votes vote down vote up
@Test
void defaultConfig_shouldUseCorrectCorsConfigValues() {
  CorsConfig corsConfig = new XConfig().corsConfig();
  assertEquals(NONE, corsConfig.origins());
  assertEquals(NONE, corsConfig.allowedRequestHeaders());
  assertEquals(NONE, corsConfig.allowedRequestMethods());
  assertFalse(corsConfig.isCorsSupportEnabled());
  assertFalse(corsConfig.isCredentialsAllowed());
  assertFalse(corsConfig.isShortCircuit());
}
 
Example #14
Source File: Http2OrHttpHandler.java    From xrpc with Apache License 2.0 5 votes vote down vote up
protected Http2OrHttpHandler(
    UrlRouter router, ServerContext xctx, CorsConfig corsConfig, int maxPayloadBytes) {
  super(ApplicationProtocolNames.HTTP_1_1);
  this.router = router;
  this.xctx = xctx;
  this.corsConfig = corsConfig;
  this.maxPayloadBytes = maxPayloadBytes;
}
 
Example #15
Source File: HttpCorsServerInitializer.java    From HttpProxy with MIT License 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new OkResponseHandler());
}
 
Example #16
Source File: HttpCorsServerInitializer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new OkResponseHandler());
}
 
Example #17
Source File: Server.java    From timely with Apache License 2.0 4 votes vote down vote up
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {

        return new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config.getHttp(), sslCtx));
                ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                ch.pipeline().addLast("compressor", new HttpContentCompressor());
                ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
                ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
                final Cors corsCfg = config.getHttp().getCors();
                final CorsConfigBuilder ccb;
                if (corsCfg.isAllowAnyOrigin()) {
                    ccb = CorsConfigBuilder.forAnyOrigin();
                } else {
                    ccb = CorsConfigBuilder.forOrigins(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
                }
                if (corsCfg.isAllowNullOrigin()) {
                    ccb.allowNullOrigin();
                }
                if (corsCfg.isAllowCredentials()) {
                    ccb.allowCredentials();
                }
                corsCfg.getAllowedMethods().stream().map(HttpMethod::valueOf).forEach(ccb::allowedRequestMethods);
                corsCfg.getAllowedHeaders().forEach(ccb::allowedRequestHeaders);
                CorsConfig cors = ccb.build();
                LOG.trace("Cors configuration: {}", cors);
                ch.pipeline().addLast("cors", new CorsHandler(cors));
                ch.pipeline().addLast("queryDecoder",
                        new timely.netty.http.HttpRequestDecoder(config.getSecurity(), config.getHttp()));
                ch.pipeline().addLast("fileServer", new HttpStaticFileServerHandler()
                        .setIgnoreSslHandshakeErrors(config.getSecurity().getServerSsl().isUseGeneratedKeypair()));
                ch.pipeline().addLast("strict", new StrictTransportHandler(config));
                ch.pipeline().addLast("login", new X509LoginRequestHandler(config.getSecurity(), config.getHttp()));
                ch.pipeline().addLast("doLogin",
                        new BasicAuthLoginRequestHandler(config.getSecurity(), config.getHttp()));
                ch.pipeline().addLast("aggregators", new HttpAggregatorsRequestHandler());
                ch.pipeline().addLast("metrics", new HttpMetricsRequestHandler(config));
                ch.pipeline().addLast("query", new HttpQueryRequestHandler(dataStore));
                ch.pipeline().addLast("search", new HttpSearchLookupRequestHandler(dataStore));
                ch.pipeline().addLast("suggest", new HttpSuggestRequestHandler(dataStore));
                ch.pipeline().addLast("version", new HttpVersionRequestHandler());
                ch.pipeline().addLast("cache", new HttpCacheRequestHandler(dataStoreCache));
                ch.pipeline().addLast("put", new HttpMetricPutHandler(dataStore));
                ch.pipeline().addLast("error", new TimelyExceptionHandler()
                        .setIgnoreSslHandshakeErrors(config.getSecurity().getServerSsl().isUseGeneratedKeypair()));

            }
        };
    }
 
Example #18
Source File: Http2CorsHandler.java    From xrpc with Apache License 2.0 4 votes vote down vote up
/** Creates a new instance with the specified {@link CorsConfig}. */
public Http2CorsHandler(CorsConfig config) {
  this.config = checkNotNull(config, "config");
}
 
Example #19
Source File: NettyUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public CorsHandlerDoNotUseOwnLogger(@Nonnull CorsConfig config) {
  super(config);
}