首页 > 解决方案 > 如何自定义 Spring DefaultCorsProcessor 抛出的“无效 CORS 请求”消息?

问题描述

当我们CORS为 Spring Boot 应用程序启用时,它会"Invalid CORS request"为带有无效源头的 REST API 调用抛出消息。DefaultCorsProcessor's这是通过以下方法抛出的。有没有办法收到customize这条消息?

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

尝试了各种选项,例如自定义异常处理程序,但没有帮助。

标签: spring-bootcors

解决方案


我认为您可以像这样注入自定义 CorsProcessor :

    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;
        }
    }

推荐阅读