Spring JPA中Curl可GET请求但POST返回403禁止访问问题
Spring应用POST请求403 Forbidden排查方案(GET请求正常)
你的场景是GET请求/activity/getall能通过HTTP Basic认证正常访问,但使用相同认证信息的POST请求/activity/post返回403,下面是几个必查的方向:
1. CSRF保护拦截(最大概率原因)
Spring Security默认对非GET请求(POST/PUT/DELETE等)开启CSRF校验,未携带CSRF Token的请求会直接被拦截返回403。
- 临时验证方案:在Spring Security配置中关闭CSRF(生产环境若为纯后端API可采用此方式,有前端交互的场景建议保留CSRF并正确传递Token):
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .httpBasic(withDefaults()); return http.build(); }
- 保留CSRF的正确做法:先通过任意可访问的GET请求获取响应头中的
X-CSRF-TOKEN,再在POST请求中携带该Token:
curl -u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "X-CSRF-TOKEN: 你的Token值" \ -X POST \ -d '{ "name":"Sleep", "criteria":"Sleep at least 8 hrs", "ini":"2022-08-30", "periodicity":"DAY", "periodicityCount":"1" }' http://localhost:5000/activity/post
2. Security配置的HTTP方法权限限制
检查Spring Security的权限规则,可能仅为GET请求开放了访问权限,POST请求被拦截:
- 确保配置中明确允许
/activity/post的POST请求通过认证:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/activity/getall").authenticated() .requestMatchers(HttpMethod.POST, "/activity/post").authenticated() .anyRequest().denyAll() ) .httpBasic(withDefaults()); return http.build(); }
3. 请求缺少Content-Type头
你的curl命令仅添加了Accept头,但未指定Content-Type: application/json,后端可能无法解析JSON请求体,进而触发权限判断异常:
- 修改curl命令,补充Content-Type头(注意换行需加反斜杠保证命令完整性):
curl -u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -X POST \ -d '{ "name":"Sleep", "criteria":"Sleep at least 8 hrs", "ini":"2022-08-30", "periodicity":"DAY", "periodicityCount":"1" }' http://localhost:5000/activity/post
4. Controller方法的额外权限注解
检查/activity/post对应的Controller方法,是否添加了@PreAuthorize这类权限注解,比如要求用户拥有ADMIN角色,但当前用户仅为普通权限:
@PostMapping("/activity/post") @PreAuthorize("hasRole('ADMIN')") // 普通用户访问会触发403 public ResponseEntity<?> createActivity(@RequestBody Activity activity) { // 业务逻辑 }
- 解决方案:要么移除多余的权限注解,要么为当前用户添加对应的角色权限。
内容的提问来源于stack exchange,提问作者Ernesto Orozco
相关产品推荐
相关产品推荐

