【发布时间】:2026-01-01 17:05:01
【问题描述】:
这真的很奇怪,我确定我错过了一些东西。这是我的 Spring Security 配置类:
@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();
}
}
所以 Postman 当我发送 GET 请求时,我得到 200 OK 状态码。但是当我遇到 POST 请求时,我得到 401 Unauthorized
更新 我发出了完全相同的 POST 请求,这次我得到了 403 Forbiden .....真的很奇怪
这里还有 Controller 代码:
@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;
}
}
【问题讨论】:
-
如何将 `.antMatchers("/task/*").permitAll() .antMatchers(HttpMethod.POST,"/task/*").permitAll()` 更改为
.antMatchers("/task/**").permitAll(),注意双*并删除第二行。 -
没有任何改变,也没有解释为什么
GET有效,而不是POST。更奇怪的是,现在我得到一个 403 Forbidden 错误 -
你能做一个最小可重复的样品吗?然后就可以更容易调试了
-
在configure方法中添加
http.csrf().disable();试试看! -
@Amitkumar 它有点工作,但知道我得到一个异常,因为它不发送正文,即使我从邮递员发送 JSON。我不知道你能不能帮我解决这个问题。但是为什么
http.csrf().disable();只需要发帖呢?
标签: java spring spring-boot spring-security http-post