Spring Boot仅GET请求可用,POST/PUT/DELETE返回401未授权问题
问题原因分析
- Security自动配置触发:哪怕你没手动添加
spring-boot-starter-security依赖,项目中其他依赖(比如部分Spring Cloud starter、webflux相关依赖)可能间接引入了Spring Security组件,触发默认安全配置。默认配置下,所有写操作(POST/PUT/DELETE)都会被拦截要求认证,而GET请求可能因默认规则被放行(不同版本略有差异)。 - 未自定义权限规则:你仅配置了Basic Auth的账号密码,但没有覆盖默认的权限拦截规则,导致写操作的认证校验逻辑未正确匹配你的配置,依然返回401。
解决方法
方法一:开发环境临时关闭Security(不推荐生产使用)
在application.properties中添加配置,直接禁用Security自动配置:
spring.security.enabled=false
方法二:自定义Security配置(推荐生产/开发通用)
根据你的Spring Boot版本,编写自定义安全配置类,明确开放GET请求权限,同时要求写操作通过Basic Auth认证:
Spring Boot 2.x 版本(使用WebSecurityConfigurerAdapter)
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.http.HttpMethod; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 配置请求权限规则 .authorizeRequests() .antMatchers(HttpMethod.GET, "/**").permitAll() // 所有GET请求无需认证 .antMatchers(HttpMethod.POST, "/**").authenticated() // POST请求需认证 .antMatchers(HttpMethod.PUT, "/**").authenticated() // PUT请求需认证 .antMatchers(HttpMethod.DELETE, "/**").authenticated() // DELETE请求需认证 .anyRequest().authenticated() // 启用Basic Auth认证方式 .and() .httpBasic(); } }
Spring Boot 3.x 版本(使用SecurityFilterChain)
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.http.HttpMethod; @Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/**").permitAll() .requestMatchers(HttpMethod.POST, "/**").authenticated() .requestMatchers(HttpMethod.PUT, "/**").authenticated() .requestMatchers(HttpMethod.DELETE, "/**").authenticated() .anyRequest().authenticated() ) .httpBasic(); return http.build(); } }
额外检查项
- 确认依赖树:用Maven命令
mvn dependency:tree或Gradle命令./gradlew dependencies查看项目依赖,确认是否有间接引入的Spring Security组件,避免不必要的自动配置。 - Postman请求配置:确保POST/PUT/DELETE请求也正确添加了Basic Auth认证信息(用户名
test、密码test),部分情况下可能仅在GET请求中配置了认证,其他请求遗漏导致401。
内容的提问来源于stack exchange,提问作者Nemgathos
相关产品推荐
相关产品推荐

