Video in progress

Senior 🌱 Spring

What security problem does this endpoint have, and how do you fix it in Spring?

@GetMapping("/api/orders/{id}")
@PreAuthorize("isAuthenticated()")
public OrderDto get(@PathVariable Long id) {
    return mapper.toDto(orderRepo.findById(id).orElseThrow());
}

This is an IDOR: any authenticated user can swap the id and see someone else's order. The ownership check has to be in the query itself (where user_id = ?) or in @PostAuthorize/the service layer.

📖 Answer

@PreAuthorize("isAuthenticated()") only checks that "someone is logged in". Anyone can try /api/orders/1001, /api/orders/1002... and harvest the whole database by guessing ids in sequence. In the OWASP API Top 10 this is number one (BOLA/IDOR).

The most reliable fix is to put ownership in the query itself:

Optional<Order> findByIdAndOwnerId(Long id, Long ownerId);
public OrderDto get(Long id, @AuthenticationPrincipal Jwt jwt) {
    Long userId = Long.valueOf(jwt.getSubject());
    return orderRepo.findByIdAndOwnerId(id, userId)
        .map(mapper::toDto)
        .orElseThrow(NotFoundException::new);   // 404, not 403: we don't reveal that it exists
}

The declarative variant, for more complex rules (say, a manager sees orders in their own department):

@PreAuthorize("@orderAccess.canRead(#id, authentication)")
public OrderDto get(Long id) { ... }

orderAccess is a plain bean, so the rule lives in one place and can be tested. @PostAuthorize("returnObject.ownerId == ...") works too, but the data is loaded first and it doesn't suit lists.

Extra protection:

  • Exposing a UUID instead of a sequential Long id makes guessing harder, but it is no substitute for the check.
  • List endpoints (/orders?userId=5) are prone to the same mistake: take the filter parameter from the token, not from the user.
  • For every endpoint, write a test that logs in as another user and swaps the id. These bugs slip past code review easily.