Spring安全配置不适用于HTTPPOST请求



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

张贴到"/用户/":只有而非登录的用户

所有其他请求都应记录在中

这是我的配置类:

@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方法会按预期工作。

我该如何解决这个问题?

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

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

参考:Spring Security CSRF

最新更新