Spring boot Spring安全配置在HTTP POST请求上不起作用

Spring boot Spring安全配置在HTTP POST请求上不起作用,spring-boot,spring-security,Spring Boot,Spring Security,我希望通过以下方式保护我的URL: 发布到“/user/”:仅那些未登录的用户 应登录所有其他请求 这是我的配置类: @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { //auth method omitted for brevity

我希望通过以下方式保护我的URL:

发布到“/user/”:仅那些未登录的用户

应登录所有其他请求

这是我的配置类:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
    //auth method omitted for brevity

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/user/").anonymous()
        .antMatchers("/**").hasAnyRole("USER")
        .and()
        .httpBasic();
    }

    @Bean //replace with bcrypt later
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
这是我的控制器类:

@RestController
@RequestMapping("/user")
public class UserController {
    
    @GetMapping("/")
    public UserShallowDTO getUser(Authentication auth) {
        return new UserShallowDTO(); //just an empty object with null properties for testing purposes
    }
    
    // @PreAuthorize("!isAuthenticated()")
    //@PostMapping("/")
    public ResponseEntity<SuccessResponse> AddUser(@RequestBody UserDTO userDTO) {
        // stuff here
    }
    
    @PostMapping("/")
    public String PostTestMethod() {
        return "hello";
    }
}
@RestController
@请求映射(“/user”)
公共类用户控制器{
@GetMapping(“/”)
public UserShallowDTO getUser(身份验证身份验证){
返回新的UserShallowDTO();//出于测试目的,只返回一个具有null属性的空对象
}
//@PreAuthorize(“!isauthorized()”)
//@邮戳(“/”)
公共响应属性AddUser(@RequestBody UserDTO UserDTO){
//这里的东西
}
@邮戳(“/”)
公共字符串PostTestMethod(){
回复“你好”;
}
}
问题是当我发帖时,它总是在邮递员身上返回401错误。 但是,当我将配置更改为GET而不是POST时,控制器的GET方法会按预期工作


如何解决此问题?

此问题与
CSRF
有关。默认情况下,
Spring
中启用了
CSRF
。 您可以在配置方法中禁用它

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .csrf().disable();
  }
参考: