You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot基础认证:PUT/DELETE请求返回401未授权问题排查

问题描述

我在CRUD风格的Rest API中配置了Basic认证,修改用户名和密码后,GET、带id的GET及POST请求均可正常工作,但调用PUT和DELETE接口时返回401 unauthorized错误。已确认用户名和密码正确,请问该问题的原因是什么?

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.0.0</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.xyztq</groupId>
   <artifactId>TodoApp2</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>TodoApp2</name>
   <description>Demo project for Spring Boot</description>
   <properties>
      <java.version>17</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-mongodb</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.project.lombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

SecurityConfiguration配置类

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
      http.httpBasic();
      http.formLogin();
    
  http.authorizeHttpRequests().requestMatchers("/todos").authenticated().and()
                .csrf().ignoringRequestMatchers("/todos")
                .and().authorizeHttpRequests().requestMatchers("/todos/{id}").authenticated().and()
                .csrf().ignoringRequestMatchers("/todos/{id}");
        return http.build();
    }
}

Controller类

@RestController
@RequestMapping("/todos")
@AllArgsConstructor
public class TodoController {
    private final TodoService todoService;

    @GetMapping
    public ResponseEntity<List<Todo>> getTodos(@RequestParam(required = false) String title){
        return new ResponseEntity<>(todoService.getTodos(title), OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Todo> getTodo(@PathVariable String id){
        return new ResponseEntity<>(todoService.getTodoById(id), OK);
    }

    @PostMapping
    public ResponseEntity<Todo> createTodo(@RequestBody Todo todo){
        return new ResponseEntity<>(todoService.createTodo(todo), OK);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> updateTodo(@PathVariable String id,@RequestBody Todo todo){
        todoService.updateTodo(id,todo);
        return new ResponseEntity<>(OK);
    }
    @PatchMapping("/{id}")
    public ResponseEntity<Void> updateDoneTodo(@PathVariable String id,@RequestBody Todo todo){
        todoService.patchTodo(id,todo);
        return new ResponseEntity<>(OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTodo(@PathVariable String id){
        todoService.deleteTodo(id);
        return new ResponseEntity<>(OK);
    }
}

问题原因及解决方案

核心原因

你的SecurityConfiguration配置存在两个关键问题:

  1. 请求规则未明确HTTP方法:当前的requestMatchers("/todos")和requestMatchers("/todos/{id}")只匹配路径,没有指定对应的HTTP方法。Spring Security的规则匹配顺序和覆盖逻辑可能导致PUT/DELETE请求未被纳入认证规则范围,被默认拦截。
  2. CSRF配置重复且无效:多次调用csrf().ignoringRequestMatchers(...)会覆盖之前的配置,而且仅忽略路径的写法对PUT/DELETE这类修改型请求的CSRF豁免不彻底,导致请求被CSRF防护拦截后返回401。

修正后的配置

重构SecurityFilterChain配置,明确路径与HTTP方法的绑定,同时统一配置CSRF豁免:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 启用Basic认证,关闭表单登录(纯API场景不需要表单登录)
        http.httpBasic()
                .and()
                .formLogin().disable();

        // 统一配置所有/todos下请求的认证规则
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/todos", "/todos/{id}").authenticated()
                .requestMatchers(HttpMethod.POST, "/todos").authenticated()
                .requestMatchers(HttpMethod.PUT, "/todos/{id}").authenticated()
                .requestMatchers(HttpMethod.PATCH, "/todos/{id}").authenticated()
                .requestMatchers(HttpMethod.DELETE, "/todos/{id}").authenticated()
                // 其他非API请求直接拒绝
                .anyRequest().denyAll());

        // 对所有/todos路径下的请求豁免CSRF检查
        http.csrf(csrf -> csrf
                .ignoringRequestMatchers("/todos/**"));

        return http.build();
    }

    // 若使用自定义用户认证,需添加以下配置(示例)
    /*
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("your-username")
                .password(passwordEncoder().encode("your-password"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    */
}

额外检查点

  • 确认配置文件中的用户名密码:如果是通过application.properties配置的,确保spring.security.user.name和spring.security.user.password是最新修改后的内容,密码无特殊字符导致解析异常。
  • 测试工具的认证缓存:比如Postman可能会缓存旧的认证信息,需手动清除后重新输入新的用户名密码测试PUT/DELETE请求。

内容的提问来源于stack exchange,提问作者GreenEngineer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 02:45:23