spring-boot - 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 方法会按预期工作。
我该如何解决这个问题?
解决方案
这个问题与CSRF
. 默认情况下CSRF
在Spring
. 您可以在配置方法中禁用它。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
推荐阅读
- azure - Azure WebJob Console Application Empty Args when calling from webhook
- audio - 对于将音频文件转录成 .txt,您会推荐什么?
- javascript - 带有 PDF 的新标签 - 下载按钮在 Chrome 上不起作用
- c++ - const 引用如何绑定到不同类型的对象
- apache-spark - pyspark: Efficiently have partitionBy write to same number of total partitions as original table
- mysql - How to get a single record in a join?
- python - Python: Start, stop, step
- javascript - 用动画关闭 div
- python - 格式化与其他变量连接的列表的打印
- javascript - 在 Openlayer 中添加热键功能