首页 > 解决方案 > Spring 安全配置不适用于 HTTP POST 请求

问题描述

我想通过以下方式保护我的网址:

发布到“/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";
    }
}

问题是当我 POST 时它不断在邮递员上返回 401 错误。但是,当我将配置更改为 GET 而不是 POST 时,控制器的 get 方法会按预期工作。

我该如何解决这个问题?

标签: spring-bootspring-security

解决方案


这个问题与CSRF. 默认情况下CSRFSpring. 您可以在配置方法中禁用它。

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

参考:Spring Security


推荐阅读