繁体   English   中英

Spring 启动 REST API POST 401 未经授权

[英]Spring Boot REST API POST 401 Unauthorized

这真的很奇怪,我确定我错过了一些东西。 这是我的 spring 安全配置 class:

@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;

    }

}

默认情况下,CSRF 保护在 Java 安全配置中启用,因此您无法通过从外部域(如 Z2567A5EC9705EB7AC2C984033E061 应用程序或 DZ 应用程序)修改 HTTP 方法(POST、PUT、...)来访问默认情况下允许使用 GET 方法。

您可以使用类似于以下的代码禁用 CSRF 保护:

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

感谢 Baeldung 在本文中教我这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM