I am using @secured in my spring boot application for a security reason. It gives me exception when i tried to access it with different roles.I can understand this. But how can I give a proper response to my front end instead of interal server error.This is my controller
@Secured("ROLE_ADMIN")
@RequestMapping(value = "/user", method = RequestMethod.POST)
public Map<String, Object> saveUser(@RequestBody User user) {
log.debug("in admin save user controller");
userService.saveUser(user);
return ResponseHandler.generateResponse(
configProp.getProperty("moderator.created"), HttpStatus.OK,
true, null);
}
This is my exception is coming. Please help I am new in it.
org.springframework.security.access.AccessDeniedException: Access is denied
从例外情况可以清楚地看出,访问的USER没有映射到访问API的正确角色,访问用户角色应该是ROLE_ADMIN。
You should put the @Secured annotation at service method level and then catch it inside controller returning your proper response.
Something like that:
UserService.java
@Secured("ROLE_ADMIN")
public void saveUser(User user) {
userRepository.save(user);
}
UserController.java
@RequestMapping(value = "/user", method = RequestMethod.POST)
public Map<String, Object> saveUser(@RequestBody User user) {
log.debug("in admin save user controller");
try {
userService.saveUser(user);
return ResponseHandler.generateResponse(
configProp.getProperty("moderator.created"), HttpStatus.OK,
true, null);
} catch(AccessDeniedException e) {
log.warn("Unauthorized", e);
return new ResponseEntity<Object>(configProp.getProperty("error.forbidden"),
HttpStatus.SC_UNAUTHORIZED);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.