【发布时间】:2019-10-19 20:14:33
【问题描述】:
我正在尝试对我的服务器(本地主机)进行一些 REST 调用,GET 方法可以正常工作,但是当我尝试通过邮递员方法 POST、PUT、DELETE 发布 JSON 对象时不起作用它说“不支持请求方法 POST " 当我再次尝试在 http 上禁用 csrf 令牌时,一切正常。
这是我的休息控制器。
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;
}
}
安全配置方法
@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
}
所以我的问题是为什么我必须禁用 csrf 才能进行 POST 调用而不是 GET 调用?还是我遗漏了什么?
【问题讨论】:
-
您是否阅读过跨站请求伪造的文档? docs.spring.io/spring-security/site/docs/5.0.x/reference/html/… 开头有一个很好的例子,解释了什么是 csrf 以及为什么以及何时应该使用 csrf 保护(也与 json 一起使用)
标签: java spring-security postman csrf