如何解决Spring Boot REST API POST 401 未经授权
这真的很奇怪,我确定我错过了一些东西。这是我的 spring 安全配置类:
@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder())
.usersByUsernameQuery(
"select username,password,enabled from user where username=?")
.authoritiesByUsernameQuery(
"select username,authority from authorities where username=?");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http .cors()
.and()
.authorizeRequests() // authorize
.antMatchers("/task/*").permitAll()
.antMatchers(HttpMethod.POST,"/task/*").permitAll()
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
因此,当我发送 GET 请求时,Postman 会收到 200 OK 状态代码。但是当我点击 POST 请求时,我得到 401 Unauthorized
更新 我提出了完全相同的 POST 请求,这次我收到了 403 Forbiden..... 真的很奇怪
还有控制器代码:
@RestController
@RequestMapping("task")
@CrossOrigin("http://localhost:3000")
public class TaskController {
@Autowired
private TaskRepo taskRepo;
//private TaskDAO taskDAO;
@GetMapping("/list")
public List<Task> getTasks(){
return taskRepo.findAll();
}
@PostMapping("/create")
public Task createTask(@RequestBody Task task) {
Task savedTask = taskRepo.save(task);
System.out.println("student id " + savedTask.getId());
return savedTask;
}
}
解决方法
在 Java 安全配置中默认启用 CSRF 保护,因此您无法通过修改 HTTP 方法(POST、PUT 等)从外部域(如 Web 应用程序或 Postman)进行访问。默认情况下允许使用 GET 方法。
您可以使用与此类似的代码禁用 CSRF 保护:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
感谢 Baeldung 在 this article 中教我。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。