如何解决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";
}
}
问题是我发帖时,它总是在邮递员上返回401错误。 但是,当我将配置更改为GET而不是POST时,控制器的get方法将按预期工作。
我该如何解决这个问题?
解决方法
此问题与CSRF
有关。默认情况下,CSRF
中的Spring
已启用。
您可以在您的配置方法中将其禁用。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。