@ PostAuthorize失败时返回404而不是403

问题描述 投票:0回答:1

假设我有以下控制器。 (假设Order.customer是该订单所属的客户,只有他们才能访问该订单。)

@RestController
@RequestMapping("/orders")
public class OrderController {
    @GetMapping
    @PostAuthorize("returnObject.customer == authentication.principal")
    public Order getOrderById(long id) {
        /* Look up the order and return it */
    }
}

查找订单后,@PostAuthorize用于确保其属于已认证的客户。如果不是,那么Spring会以403禁止响应。

这样的实现有一个问题:客户可以区分不存在的订单和他们无权访问的订单。理想情况下,在两种情况下都应返回404。

虽然可以通过将Authentication注入处理程序方法并在其中实现自定义逻辑来解决,但有没有办法使用@PostAuthorize或类似的声明性API来实现这一点?

java spring spring-security
1个回答
0
投票

您可以尝试使用ControllerAdvice来捕获和转换PostAuthorize引发的AccessDeniedException。

@RestControllerAdvice
public class ExceptionHandlerController {

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(AccessDeniedException.class)
    public String handleAccessDenied(AccessDeniedException e) {
        return "nothing here"; // or a proper object
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.