3

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;

    }

}
Panagiss
  • 3,154
  • 2
  • 20
  • 34
  • What about changing ` .antMatchers("/task/*").permitAll() .antMatchers(HttpMethod.POST,"/task/*").permitAll()` to `.antMatchers("/task/**").permitAll()`, notice the double `*` and removing the second line. – ch271828n Dec 31 '20 at 09:59
  • nothing changed, also it doesn't explain why ```GET``` works and not ```POST```. Even more strange is that now i get a 403 Forbidden error – Panagiss Dec 31 '20 at 10:04
  • Could you make a minimum reproducible sample? Then it can be debugged easier – ch271828n Dec 31 '20 at 10:06
  • 1
    Add `http.csrf().disable();` in configure method and try! – Amit kumar Dec 31 '20 at 10:08
  • @Amitkumar it kind of worked, but know i get an exception cause it does't send the body, even tho i send a JSON from postman. I don't know if you can help me with that. But why ```http.csrf().disable();``` was needed only for post? – Panagiss Dec 31 '20 at 10:21
  • When you enable spring security via `@EnableWebSecurity` it internally enables CSRF as well. So, This has to be handled to prevent Forbidden errors. – Amit kumar Dec 31 '20 at 10:25
  • the thing now is that i cannot send the Body from Post request. Server throws exception cause Body is full of ```null``` even tho i send a Body from Postman – Panagiss Dec 31 '20 at 10:27
  • Try `@PostMapping(path = "/create", consumes = "application/json", produces = "application/json")` – Amit kumar Dec 31 '20 at 10:29
  • it didn't work. I made a ```println()``` before throwing the exception and it's what i said. For some reason it don't get anything. Here is what the println printed ```Task{id=0, teachingHours=null, surveillanceHours=null, proofReading=null, isActive=false, isValidated=false, candidateId=null, supervisorId=null} ``` – Panagiss Dec 31 '20 at 10:35
  • turn on spring security debugging https://stackoverflow.com/a/47729991/1840146 and it will tell you why you are getting the error messages – Toerktumlare Dec 31 '20 at 18:00
  • I have managed to overcome some problems. But know im facing a bigger one. Check here https://stackoverflow.com/questions/65525635/how-to-save-entity-and-child-when-the-child-already-exists-in-spring-data-jpa-re . – Panagiss Jan 01 '21 at 12:17

1 Answers1

7

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.

Eneko
  • 1,709
  • 1
  • 16
  • 25