I'm trying to do some REST calls to my server(localhost), GET methods working properly but, when I try to post JSON objects through postman methods POST, PUT, DELETE not working It says "Request method POST not supported" when I try again disabling csrf tokens on http, everything works well.
Here is my Rest Controller.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.kish.Service.CustomerService;
import com.kish.entity.Customer;
@RestController
@RequestMapping("/api")
public class CRMRestController {
public CRMRestController() {
}
@Autowired
private CustomerService customerService;
@GetMapping("/customers")
public List<Customer> getCustomers() {
return customerService.getCustomers();
}
@GetMapping("/customers/{customerId}")
public Customer getCustomer(@PathVariable int customerId) {
if((customerService.getCustomer(customerId) == null)) {
throw new CustomerNotFoundException("No customer found in the database" + customerId);
}
return customerService.getCustomer(customerId);
}
@PostMapping("/customers")
public Customer addCustomer(@RequestBody Customer customer) {
customer.setId(0);
customerService.saveCustomer(customer);
return customer;
}
@PutMapping("/customers")
public Customer updateCustomer(@RequestBody Customer customer) {
customerService.saveCustomer(customer);
return customer;
}
@DeleteMapping("/customers/{customerId}")
public String deleteCustomer(@PathVariable int customerId) {
if((customerService.getCustomer(customerId)) == null) throw new CustomerNotFoundException("request valid data");
customerService.deleteCustomer(customerId);
return "deleted customer id is " + customerId;
}
}
security config method
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests() // restrict access based on the request coming in.
.antMatchers("/customer/list").hasRole("EMPLOYEE")
.antMatchers("/customer/Actions/**").hasAnyRole("ADMIN","MANAGER")
.and()
.formLogin()
.loginPage("/showMyLoginForm")
.loginProcessingUrl("/authenticateTheUser") // it checks the
.permitAll()
.and()
.logout()
.permitAll()
.and().exceptionHandling().accessDeniedPage("/access-denied"); // Spring Security uses this page for Access denied pages
}
So my question is why I have to disable csrf in order to do POST calls but not for GET calls? or did I missing something?