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)
@ResponseBody
public 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();
}
In stead of raiseing an Exception which leads to InternalServerExcetption
, I 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 prefere a solution, which works as well for other Erros like 404. What would be the easiest way to achieve that goal?