如何自定义Spring DefaultCorsProcessor抛出的“无效CORS请求”消息?

tv6aics1  于 2023-02-04  发布在  Spring
关注(0)|答案(1)|浏览(145)

当我们为Sping Boot 应用程序启用CORS时,它会为具有无效源标头的REST API调用抛出"Invalid CORS request"消息。这是由下面的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();
}

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

yfwxisqw

yfwxisqw1#

我认为您可以像这样注入自定义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;
        }
    }

相关问题