我遵循了一个针对 spring boot 新手的简单教程,并设置了我的第一个 Controller 和一些 API 调用。但是,我能够调用 GET,但 POST 总是给我来自 postman 和 curl 的 403 错误代码。
这是我的相关代码
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
这是我的 Controller 代码
@ApiOperation(value = "Create a new order")
@RequestMapping(value = "/orders", method = RequestMethod.POST, produces = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public Order createOrder(
@ApiParam(value = "New order object", required = true)
@RequestBody Order newOrder) {
newOrder.setSymbol(newOrder.getSymbol().toUpperCase());
return orderRepository.save(newOrder);
}
这是 http 响应:
{
"timestamp": "2019-10-08T19:57:03.487+0000",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/v1/orders"
}
我这样请求 curl
curl --location --request POST "http://localhost:8080/api/v1/orders --data "test"
我知道这不是 CORS 问题,我已经尝试了其他几种身份验证方法,它们都给出了 403(不是 401)
最佳答案
你可以试试看CSRF参数。
HttpSecurity POST 403 Forbidden
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
关于java - 继续从 spring boot 示例代码中获取 403 禁止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58293394/