如何自定义Spring DefaultCorsProcessor抛出"Invalid CORS request"消息?



当我们为Spring 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();
}

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

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

最新更新