如何解决 Spring Boot Post 请求中的 403 错误

新手上路,请多包涵

我是春季靴子休息服务的新手。我使用 maven 项目在 spring boot 中开发了一些 rest api。

我已经成功开发了 GetPost Api。我的 GET 方法在邮递员和移动设备中正常工作。 当我试图从邮递员中使用 post 方法时,它可以正常工作,但从移动端使用它会出现 403 禁止错误。

这是我的配置:

 spring.datasource.url = jdbc:mysql://localhost/sampledb?useSSL=false
spring.datasource.username = te
spring.datasource.password = test
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

请建议我如何解决错误。

在此处输入图像描述

原文由 Harshal Deshmukh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

您必须禁用 csrf 保护,因为它在 spring security 中默认启用:在这里您可以看到允许 cors 来源的代码。

 import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.cors().and().csrf().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

原文由 Ezzat Eissa 发布,翻译遵循 CC BY-SA 4.0 许可协议

可能的原因:

  1. 邮递员完成的请求与移动端完成的请求不同(uri、方法、标头)
  2. 令牌无效
  3. CORS(阅读一些关于它的内容,谷歌充满了文章)将 @CrossOrigin 注释添加到您的控制器。
  4. 移动应用程序在执行 POST 之前执行 OPTION 请求,而您阻止了 OPTION 请求。如果邮递员也阻止了 OPTION 请求,请添加属性 spring.mvc.dispatch-options-request=true 。此外,如果您使用的是 spring security,您还必须明确允许 OPTION 请求。

原文由 desoss 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题