1

I have a problem with DELETE method in spring. I'm using JWT and sending it in request header but GET/POST/PATCH works, DELETE don't..I don't really know why. Even via postman I'm not authorized 401 to delete item but I can get/patch/post a new one... Here is my code of controllers:

@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)
@RestController
public class JwtAuthenticationController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @Autowired
    private CarDetailsService carDetailsService;


    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {

        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());

        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());

        final String token = jwtTokenUtil.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity<?> saveUser(@RequestBody UserDTO user) throws Exception {
        return ResponseEntity.ok(userDetailsService.save(user));
    }

    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREDENTIALS", e);
        }
    }

    @RequestMapping(value = "/car", method = RequestMethod.POST)
    public ResponseEntity<?> getRents(@RequestBody CarDTO car) throws Exception {
        return ResponseEntity.ok(carDetailsService.saveCar(car));
    }



    @RequestMapping(value ="/cars", method = RequestMethod.GET)
    public ResponseEntity<?> getCars() throws Exception{
        return ResponseEntity.ok(carDetailsService.getAllCars());
    }


    @PatchMapping("/cars/{id}")
    public ResponseEntity<?>  partialUpdate(@RequestBody PartialCarDTO partialCar, @PathVariable("id") Integer id){
        return ResponseEntity.ok(carDetailsService.updateCar(partialCar,id));
    }

    @RequestMapping(value = "/cars/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<?> deleteCar(@RequestBody PartialCarDTO partialCar, @PathVariable("id") Integer id){
        return ResponseEntity.ok(carDetailsService.deleteCar(partialCar,id));
    }
Snooze Snoze
  • 109
  • 1
  • 10
  • What is your web security configuration? Maybe [this](https://www.baeldung.com/spring-security-cors-preflight) article could help? More possible [solutions](https://stackoverflow.com/questions/40418441) – MartinBG Dec 12 '19 at 22:39

2 Answers2

0

A good answer here: https://stackoverflow.com/a/299696/4573580

If a DELETE request includes an entity body, the body is ignored [...]

Dmitry Ionash
  • 763
  • 5
  • 11
0

I deleted PartialCarDTO from requestmapping and via postman it is possible to delete entity, but in my rest api it's not .. :/ I tried a lot of variations but without success. Even if i pass NULL instead of payload in axios while keeping headers like authorization with my token, content type and access control allow origin. No I really don't know where is the problem. Always 401. Do You have any ideas?

  return new Promise((resolve, reject) => {
                    let id=payload.id;
                    let url="http://localhost:8080/cars/"+id
                    let config = {
                        headers: {
                            "Authorization": "Bearer "+localStorage.getItem('token'),
                            "Content-Type": "application/json",
                            "Access-Control-Allow-Origin": "*"
                          }
                        }  

                    axios.delete(url, payload, config)
                    .then(({data,status}) => {
                        if(status === 200){
                            resolve(true);
                        }
                    })
                    .catch(error=> {
                        reject(error);
                    })
                }
Snooze Snoze
  • 109
  • 1
  • 10