Search code examples
spring-bootcors

How to customise "Invalid CORS request" message thrown by Spring DefaultCorsProcessor?


When we enable CORS for a Spring Boot application, it throws "Invalid CORS request" message for the REST API calls with invalid origin header. This is thrown by DefaultCorsProcessor's below method. Is there a way to customize this message?

protected void rejectRequest(ServerHttpResponse response) throws IOException {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getBody().write("Invalid CORS request".getBytes(StandardCharsets.UTF_8));
        response.flush();
}

Tried various options like custom exception handler but didn't help.


Solution

  • I think you could inject a custom CorsProcessor like that:

        import java.io.IOException;
        
        import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
        import org.springframework.http.server.ServerHttpResponse;
        import org.springframework.stereotype.Component;
        import org.springframework.web.cors.DefaultCorsProcessor;
        import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
        
        @Component
        public class CustomWebMvcRegistrations implements WebMvcRegistrations {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                RequestMappingHandlerMapping rhm = new RequestMappingHandlerMapping();
                rhm.setCorsProcessor(new DefaultCorsProcessor() {
                    @Override
                    protected void rejectRequest(ServerHttpResponse response) throws IOException {
                        // DO WHATEVER YOU WANT
                        super.rejectRequest(response);
                    }
                });
                return rhm;
            }
        }