使用Spring Boot + Vaadin使用REST Api实现一个简单的Web应用程序。此外,在项目中连接了安全性,使用登录密码进行了简单的登录。Get()请求工作正常,但在PUT、POST、DELETE请求中出现403 "禁止"错误。
我尝试使用http.httpBasic().and().csrf().disable()
方法禁用csrf,它没有帮助,而且在生产中也不推荐这样做。
我还尝试在antMatchers()
中添加一个请求类型,如下所示:http.httpBasic().and().authorizeRequests().antMatchers(HttpMethod.POST,"/**").permitAll()
,也无济于事。
配置类:
@EnableWebSecurity
@Configuration
public class SecurityConfig extends VaadinWebSecurity {
private static class SimpleInMemoryUserDetailsManager extends InMemoryUserDetailsManager {
public SimpleInMemoryUserDetailsManager() {
createUser(Manager.withUsername("manager1")
.password("{noop}123")
.roles(ROLE_MANAGER)
.build());
createUser(Manager.withUsername("manager2")
.password("{noop}123")
.roles(ROLE_MANAGER)
.build());
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/enterprises/\*\*").hasRole(ROLE_MANAGER);
super.configure(http);
setLoginView(http, LoginView.class);
}
@Bean
public InMemoryUserDetailsManager enterprisesService() {
return new SimpleInMemoryUserDetailsManager();
}
}
静止控制器:
@org.springframework.web.bind.annotation.RestController
@RequestMapping(path = "/")
public class RestController {
@Autowired
private VehiclesRepository vehiclesRepository;
@Autowired
private EnterprisesRepository enterprisesRepository;
@Autowired
private DriversRepository driversRepository;
@Autowired
private ManagersRepository managersRepository;
@GetMapping(
path = "/vehicles",
produces = "application/json")
public VehiclesDto getVehicles() {
VehiclesDto vehiclesDto = new VehiclesDto();
for (Vehicle vehicle : vehiclesRepository.findAll()) {
vehiclesDto.getVehicles().add(vehicle);
}
return vehiclesDto;
}
@GetMapping(
path = "/enterprises",
produces = "application/json")
public @ResponseBody EnterprisesDto getEnterprises(@RequestParam("managerId") String managerId) {
Manager manager = null;
for (Manager managerFromRepo : managersRepository.findAll()) {
if (managerFromRepo.getId().equals(Long.parseLong(managerId))) {
manager = managerFromRepo;
break;
}
}
EnterprisesDto enterprisesDto = new EnterprisesDto();
if (manager == null) return enterprisesDto;
for (Enterprise enterprise : enterprisesRepository.findAll()) {
if (manager.getEnterprises().contains(enterprise.getId()))
enterprisesDto.getEnterprises().add(enterprise);
}
return enterprisesDto;
}
@GetMapping(
path = "/drivers",
produces = "application/json")
public DriversDto getDrivers() {
DriversDto driversDto = new DriversDto();
for (Driver driver : driversRepository.findAll()) {
driversDto.getDrivers().add(driver);
}
return driversDto;
}
@PostMapping("/createVehicle")
public @ResponseBody String createVehicle(@RequestBody String info) {
return "it works!!!";
}
@DeleteMapping("/deleteVehicle")
public @ResponseBody String deleteVehicle(){
return "it works!!!";
}
}
使用基本身份验证通过Postman测试请求。
1条答案
按热度按时间jk9hmnmh1#
您可以仅对您的API禁用CSRF: