Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot REST API POST 401 Unauthorized

It is really strange and im sure im missing something. Here is my spring Security config 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();
    }

}

So on Postman when i send a GET request i get 200 OK status code. But when i hit a POST request i get 401 Unauthorized

UPDATE I have made the exact same POST request and i got 403 Forbiden this time..... really strange

Also here is the Controller code:

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

    }

}
like image 341
Panagiss Avatar asked Aug 19 '26 18:08

Panagiss


1 Answers

CSRF protection is enabled by default in the Java Security configuration, so you cannot access with modifying HTTP methods (POST, PUT, ...) from an external domain (like a web app or Postman). GET method is allowed by default.

You can disable CSRF protection with code similar to this:

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

Thank you for Baeldung for teaching me that in this article.

like image 93
Eneko Avatar answered Aug 21 '26 09:08

Eneko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!