我正在使用 Spring @RolesAllowed
来保护我的 API(方法),但我想更改未经授权的用户调用方法时发生的情况。当前的行为是 Spring 抛出 HTTP 403 错误。这很棒,但我只想在 403 响应正文中添加一个额外的错误代码,以便能够区分不同场景中的访问被拒绝错误。
我很难弄清楚 @RolesAllowed
注释的实现位置。有人遇到过吗?或者试图改变它的行为?
我的 Controller 中的方法当前如下所示:
@RolesAllowed({"ROLE_DEFENDANT", "ROLE_ADMIN"})
@RequestMapping(method = RequestMethod.POST, value = "/{caseId}/owner")
public ResponseEntity<?> assignOwner(@PathVariable String caseId) {
// method implementation
}
最佳答案
执行此操作的另一种方法是使用异常处理程序类和 @ExceptionHandler 注释。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<?> handleAccessDenied(HttpServletRequest request, AccessDeniedException ex) {
// exception handling logic
if (request.getUserPrincipal() == null) {
// user is not logged in
} else {
// user is logged in but doesn't have permission to the requested resource
}
// return whatever response you'd like
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
关于java - 修改 Spring @RolesAllowed 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322610/