java - 继续从 spring boot 示例代码中获取 403 禁止

标签 java spring-boot http authentication

我遵循了一个针对 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/

相关文章:

spring-boot - 升级到2.2.4后无法运行Spring Boot应用程序:方法不存在

java - "Expected ' , ' instead of ' ' "Spring Boot POST 方法响应消息

http - 可恢复.js : HTTP response errors (deployed to heroku or nodejitsu)

java - 为jsp使用javascript变量

java - 为什么我的 JDialog 中的 JButton 不起作用?固定的

spring-boot - 使用 Spring Cloud Stream kafka 动态更改实例索引

javascript - 如何从 Express 中的 API 获取要在 Angular 中显示的数据?

asp.net - .Net System.Net.HttpWebRequest 和身份验证 Cookie

java - 无需序列化的深度克隆

java - Java 内存模型中的实例变量