Within my API I like to protect the user details endpoints, so that normal logged in users can only access their user profile. Therefor I am writing the controller:
@RequestMapping(value = URL_USER +"/{id}", method = RequestMethod.GET)@ResponseBodypublic PersistentEntityResource get(PersistentEntityResourceAssembler persistentEntityResourceAssembler, @PathVariable Long id) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ApplicationUser loggedInUser = applicationUserService.findByUsername(authentication.getName()); ApplicationUser applicationUser = applicationUserService.findById(id); if (applicationUser.getId().equals(loggedInUser.getId())) { return persistentEntityResourceAssembler.toFullResource(applicationUser); } throw new IllegalAccessException();}
Instead of raising an exception which leads to InternalServerExcetption
, I would like to return the default spring boot error json, like the following:
{"timestamp": "2019-05-08T11:42:23.064+0000","status": 403,"error": "Forbidden","message": "Access Denied","path": "/user/2"}
I would prefer a solution, which works well for other erros like 404. What would be the easiest way to achieve that goal?