Reputation: 3720
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;
}
}
Upvotes: 3
Views: 10387
Reputation: 2107
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.
Upvotes: 7