【问题标题】:403 error when requesting POST or PUT during Spring RestAPI development在 Spring RestAPI 开发期间请求 POST 或 PUT 时出现 403 错误
【发布时间】:2021-07-15 16:09:35
【问题描述】:

我正在尝试在应用了 Spring 5 + Spring Security 5 的项目中实现和使用 Rest API。

在本地运行 Tomcat 后使用 Postman 进行测试时

url: http://localhost:8080/api~

已确认get、post、put等请求正常。

我将此项目上传到 https 服务器,并在本地 Postman 中测试服务器上的 api,

put、post等请求出现403禁止错误,get请求除外。

我google了一下,说是Spring Security的csrf问题+cors处理问题。


所以我就这样改了代码。

  • WebSecurityConfig
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/").permitAll()                   
                   ~
                   .anyRequest().permitAll()
                .and()
                    .formLogin()
                 ~                  
                .and()
                    .logout()
               ~
                .and()
                    .httpBasic().disable().cors().configurationSource(corsConfigurationSource())
                .and()
                    .sessionManagement()
                    ~
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }
  • WebMvcConfig
@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedOrigins("*");
    }
  • 控制器
@CrossOrigin("*")

但是在飞行请求中它通常返回 200,但是在这个请求中我仍然得到 403。

哪一部分错了?如果您让我知道,我将不胜感激:)

【问题讨论】:

  • 嗨,曼迪,欢迎来到 StackOverflow。这不是一个真正的答案。如果您想添加更多信息或提供不同的示例,请编辑您的原始问题

标签: spring spring-security cors http-status-code-403


【解决方案1】:

在您的配置中,通过 HttpSecurity 构建器添加 Cors 过滤器。 即

Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
        .........

这将启用 PUT 和 POST 使用的 cors 预检请求。 您不需要包含 CorsConfigurationSource,只需确保您的控制器中也有 @CrossOrigin 注释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2019-06-21
    • 2019-07-17
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 2015-12-23
    相关资源
    最近更新 更多