javaproject-reactorreactor-netty

How to implement CORS in Reactor Netty?


As you know, the CORS standards include initially sending an OPTIONS request to check validity, and I decided to release the processing of OPTIONS requests in the handler, but a problem arose to return a boolean value, and only process OPTIONS requests, and skip the rest in runOn, perhaps you know others ways to handle CORS helper requests?

public void run() {
    HttpServer.create()
            .host(this.config.getHost())
            .port(this.config.getPort())
            .runOn(eventLoopGroup.newEventLoopGroup())
            .protocol(HttpProtocol.HTTP11)
            .handle((request, response) -> {
                if (request.method().equals(HttpMethod.OPTIONS)) 
                    return response
                        .header("Access-Control-Allow-Origin", "*")
                        .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
                        .header("Access-Control-Allow-Headers", "Content-Type, Authorization")
                        .sendHeaders();
                else 
                    ???????
            })
            .route(this.provider::run)
            .bindUntilJavaShutdown(Duration.ofSeconds(30), this::onStart);
}

Solution

  • If anyone suddenly needs

    private @NotNull CorsConfig getCorsConfig() {
        return CorsConfigBuilder.forAnyOrigin()
                .allowNullOrigin()
                .allowCredentials()
                .allowedRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PUT, HttpMethod.PATCH)
                .allowedRequestHeaders("Content-Type", "Authorization")
                .build();
    }
    
    public void run() {
        HttpServer.create()
                .host(this.config.getHost())
                .port(this.config.getPort())
                .protocol(HttpProtocol.HTTP11)
                .doOnConnection(this::handler)
                .route(this.provider::run)
                .bindUntilJavaShutdown(Duration.ofSeconds(30), this::onStart);
    }
    
    private void addHandler() {
        this.connection.addHandlerLast(new CorsHandler(getCorsConfig()));
    }