spring-boot - 如何自定义 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();
}
尝试了各种选项,例如自定义异常处理程序,但没有帮助。
解决方案
我认为您可以像这样注入自定义 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;
}
}
推荐阅读
- pandas - 从函数的返回值创建数据框
- python - 在 Python 中通过嵌套的 Json/dict 解析
- php - 无法使用 Mssql Pconnect 连接
- python - binance.exceptions.BinanceAPIException: APIError(code=-1013): Filter failure: LOT_SIZE
- javascript - IE11:如何在 Internet Explorer 中的 React 中填充 `Array.values().next()`?
- numbers - 替换文件名中的 2 数字以在 python 中获得正确的格式
- datagrip - Datagrip - 单击左侧面板中的模式名称时不显示表名称
- android - 跨平台的 Firebase 有效负载 json 不起作用
- javascript - 如何在 RMarkdown 的代码块中使用 JavaScript?
- identity - dbt - 如何让创建表创建一个自动增量列