当我们为 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;
}
}
如果只有一个接收者不允许访问某些资源,是否还需要更改响应消息?值得实施吗?我不知道如何使用上述方法来做到这一点。有人有这个解决方案的新版本吗?