Skip to lesson

Owner checks: a customer sees only their own orders

Asha may read her orders, but Ravi's order 14 must look exactly like an order that does not exist. A role check cannot give her that, because "whose order is this?" is a question about data, not about URLs.

The bug: any customer can read any order

IDOR (Insecure Direct Object Reference) is the bug where a server takes an id from the request and returns that object without checking that the caller may see it.

ShopLite checked that the caller was a customer, but never whose order it was. Asha only had to change 1 to 14 in the URL to read Ravi's order.

Example 1 · The bug: Asha reads Ravi's order 14

Runs in: the shoplite-api Spring Boot project

Terminal
// OrderService (part) before this lesson: any signed-in caller gets any orderpublic OrderResponse get(Integer id) {    Order order = orders.findWithItemsById(id)            .orElseThrow(() -> new ResourceNotFoundException("Order " + id + " was not found."));    return OrderMapper.toResponse(order, time);}// SecurityConfig (part): the URL rule only asks "is this a signed-in customer or admin?".requestMatchers(HttpMethod.GET, "/api/v1/orders/*", "/api/v1/orders/*/items")    .hasAnyRole("CUSTOMER", "ADMIN")# Asha (customer 1) asks for order 14, which is Ravi'scurl -i http://localhost:8080/api/v1/orders/14 -H "Authorization: Bearer $ASHA"
Output
HTTP/1.1 200
Content-Type: application/json

{"id":14,"customerId":2,"addressId":3,"status":"SHIPPED","orderedAt":"2026-09-21T21:05:00+05:30","items":[{"productId":1,"sku":"MOB-RN13","productName":"Redmi Note 13 5G","quantity":1,"unitPrice":17999.00,"lineTotal":17999.00},{"productId":6,"sku":"ACC-AD141","productName":"boAt Airdopes 141","quantity":1,"unitPrice":1299.00,"lineTotal":1299.00}],"total":19298.00}

What this code does

  • The URL rule passed (Asha is a customer) and the service loaded order 14 by id alone, so the response is Ravi's order: customerId 2, his address 3 and his items.
  • Nothing in the request was forged. Asha used her own valid token and changed one number in the URL.
  • This run is from the code before this lesson's fix; the rest of the lesson changes the service, not the URL rules.

URL rules cannot fix this. The rule sees /api/v1/orders/14 and a customer token, but "who owns order 14" lives in the database, so the check has to be in the code that loads the order.

IDOR is part of Broken Access Control, number A01 in the OWASP Top 10 2025.

Fix 1: query by owner and answer 404

Querying by owner means the database query itself includes the owner: where o.id = :id and o.customer.id = :customerId. Another customer's order is simply not found, exactly like an id that does not exist.

The owner becomes part of the query. Another customer's order then comes back empty. This is the repository method, and what Asha sees for order 14.

Example 2 · Fix 1: findWithItemsByIdAndCustomerId and loadVisible

Runs in: the shoplite-api Spring Boot project

Java
// src/main/java/com/shoplite/order/OrderRepository.java (part)/** The order only if it belongs to this customer: someone else's order is simply "not found". */@Query("""        select o from Order o        join fetch o.items i        join fetch i.product        where o.id = :id and o.customer.id = :customerId""")Optional<Order> findWithItemsByIdAndCustomerId(@Param("id") Integer id, @Param("customerId") Integer customerId);
// src/main/java/com/shoplite/order/OrderService.java (part)public OrderResponse get(Integer id, CurrentUser caller) {    return OrderMapper.toResponse(loadVisible(id, caller), time);}
public List<OrderItemResponse> items(Integer id, CurrentUser caller) {    return OrderMapper.toResponse(loadVisible(id, caller), time).items();}
/** Fix 1: ask the database only for orders the caller may see. Admins see every order. */private Order loadVisible(Integer id, CurrentUser caller) {    Optional<Order> order = caller.isAdmin()            ? orders.findWithItemsById(id)            : orders.findWithItemsByIdAndCustomerId(id, caller.requireCustomerId());    return order.orElseThrow(() -> notFound(id));}
// src/main/java/com/shoplite/order/OrderController.java (part)@GetMapping("/{id}")OrderResponse get(@PathVariable Integer id, @AuthenticationPrincipal Jwt jwt) {    return service.get(id, CurrentUser.from(jwt));}
Output
$ curl -i http://localhost:8080/api/v1/orders/14 -H "Authorization: Bearer $ASHA"
HTTP/1.1 404
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 14 was not found.","instance":"/api/v1/orders/14"}

$ curl -i http://localhost:8080/api/v1/orders/999 -H "Authorization: Bearer $ASHA"
HTTP/1.1 404
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 999 was not found.","instance":"/api/v1/orders/999"}

$ curl -i http://localhost:8080/api/v1/orders/14/items -H "Authorization: Bearer $ASHA"
HTTP/1.1 404
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 14 was not found.","instance":"/api/v1/orders/14/items"}

What this code does

  • The owner is part of the where clause, so MySQL returns no row for someone else's order and the service throws the usual ResourceNotFoundException.
  • Order 14 (Ravi's) and order 999 (does not exist) get the same 404 body, so Asha cannot tell them apart.
  • items uses the same loadVisible, so /orders/14/items is closed too. Every endpoint that takes an order id needs this, not just the first one.

Both cases give the same 404 with the same detail. A 403 would say "this order exists, but not for you", which tells an attacker which ids are real. The rule in SECURITY.md is: own, else 404.

The controller passes the caller, read from the verified token, into the service as a CurrentUser. The service never trusts a customer id from the URL or the body.

Predict the output

Which status does Asha get?

Asha is customer 1. Orders 1, 3 and 10 are hers; order 14 is Ravi's.

Round 1 of 3

Asha calls GET /api/v1/orders/1.

Optional<Order> order = orders.findWithItemsByIdAndCustomerId(1, 1);
return order.orElseThrow(() -> notFound(1));

Fix 2: an owner check in the service

An owner check makes sure the caller owns the object, or is an admin. Done in code, it loads the object first and then compares its owner with the caller.

In cancel the order row is loaded and locked with SELECT ... FOR UPDATE, so a second query only for the owner would be wasteful. The owner check runs right after loading.

Example 3 · Fix 2: requireVisible in cancel

Runs in: the shoplite-api Spring Boot project

Java
// src/main/java/com/shoplite/order/OrderService.java (part)@Transactionalpublic OrderResponse cancel(Integer id, CurrentUser caller) {    Order order = orders.findWithItemsByIdForUpdate(id).orElseThrow(() -> notFound(id));    requireVisible(order, caller);                       // before any rule that could reveal the order    if (order.getStatus() != OrderStatus.PLACED) {        throw new OrderCannotBeCancelledException(id, order.getStatus());    }    for (OrderItem item : order.getItems()) {        productService.returnStock(item.getProduct().getId(), item.getQuantity());    }    order.setStatus(OrderStatus.CANCELLED);    log.info("Order {} cancelled by user {}; stock returned for {} items", id, caller.userId(),            order.getItems().size());    return OrderMapper.toResponse(order, time);}
/** Fix 2: the order is already loaded (and locked); check its owner in code. */private static void requireVisible(Order order, CurrentUser caller) {    boolean owner = order.getCustomer().getId().equals(caller.customerId());    if (!caller.isAdmin() && !owner) {        throw notFound(order.getId());                   // same answer as a missing order    }}
Output
$ curl -i -X POST http://localhost:8080/api/v1/orders/14/cancel -H "Authorization: Bearer $ASHA"
HTTP/1.1 404
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 14 was not found.","instance":"/api/v1/orders/14/cancel"}

What this code does

  • cancel must lock the order row anyway, so it loads by id and then calls requireVisible before looking at the status.
  • Order 14 is SHIPPED. Because the owner check runs first, Asha sees 404, not the 409 that would reveal the order's status.
  • The log line records the user id of the caller, which helps when someone reports a cancelled order they did not cancel.

The check must come before every other rule. If cancel checked the status first, Asha would get "409: Order 14 is SHIPPED and can no longer be cancelled." for Ravi's order, which reveals that it exists and how far it has travelled.

Both fixes give the same answer. Fix 1 is safer for reads, because no other person's data is ever loaded into memory. Fix 2 fits when the object must be loaded anyway.

Order of execution

Order the steps of cancel

Tap the steps in the order cancel(id, caller) runs them.

Admins see every order

CurrentUser is a small record built from the verified token: the user id (sub), the customerId claim and the roles. Services use it to decide whether the caller is the owner or an admin.

The access table says an order is visible to its owner or to an admin. CurrentUser carries the caller from the token into every service, so the service can decide.

Example 4 · src/main/java/com/shoplite/common/security/CurrentUser.java

Runs in: the shoplite-api Spring Boot project

CurrentUser.javaJava
package com.shoplite.common.security;
import java.util.List;import java.util.Set;
import org.springframework.security.access.AccessDeniedException;import org.springframework.security.oauth2.jwt.Jwt;
/** * Who is calling, read from the verified access token. Controllers build it and pass it to services, * so services never read the SecurityContext themselves and are easy to test. */public record CurrentUser(Integer userId, Integer customerId, Set<String> roles) {
    public static CurrentUser from(Jwt jwt) {        List<String> roles = jwt.getClaimAsStringList("roles");        Number customerId = jwt.getClaim("customerId");        return new CurrentUser(Integer.valueOf(jwt.getSubject()),                customerId == null ? null : customerId.intValue(),                roles == null ? Set.of() : Set.copyOf(roles));    }
    public boolean isAdmin() {        return roles.contains("ADMIN");    }
    /** The caller's own customer id; a staff account has none, so /me endpoints are not for it. */    public Integer requireCustomerId() {        if (customerId == null) {            throw new AccessDeniedException("This account has no customer profile.");        }        return customerId;    }}
Output
$ curl -i http://localhost:8080/api/v1/orders/14 -H "Authorization: Bearer $ADMIN"
HTTP/1.1 200
Content-Type: application/json

{"id":14,"customerId":2,"addressId":3,"status":"SHIPPED","orderedAt":"2026-09-21T21:05:00+05:30","items":[{"productId":1,"sku":"MOB-RN13","productName":"Redmi Note 13 5G","quantity":1,"unitPrice":17999.00,"lineTotal":17999.00},{"productId":6,"sku":"ACC-AD141","productName":"boAt Airdopes 141","quantity":1,"unitPrice":1299.00,"lineTotal":1299.00}],"total":19298.00}

# Sneha signed up a minute ago (customer 9, no orders yet)
$ curl -i http://localhost:8080/api/v1/orders/1 -H "Authorization: Bearer $SNEHA"
HTTP/1.1 404
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 1 was not found.","instance":"/api/v1/orders/1"}

$ curl -i http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer $SNEHA"
HTTP/1.1 200
Content-Type: application/json

{"content":[],"page":0,"size":20,"totalElements":0,"totalPages":0}

What this code does

  • CurrentUser.from(jwt) reads only verified claims: sub (user id), customerId and roles. Nothing comes from the request body or URL.
  • The admin reads Ravi's order 14 (200). Sneha, a new customer, gets 404 for Asha's order 1 and an empty page for her own list.
  • requireCustomerId() is the guard for accounts without a customer profile: a staff token can never be treated as some customer's.

In loadVisible an admin uses the plain findWithItemsById, and everyone else uses the owner query. In requireVisible, !caller.isAdmin() && !owner throws 404. An admin account has no customer row, so requireCustomerId() throws AccessDeniedException (403) if such an account ever reaches a customer-only path.

A brand-new customer is the best test of the rule: Sneha has no orders, so every existing order id must be 404 for her, and her own list must be empty.

/me endpoints: the client never sends its own id

A /me endpoint is a URL for the signed-in user's own data, such as GET /api/v1/me/orders. The server takes the customer id from the token, so there is no id in the URL or body for a client to change.

The controller takes the customer from the token, so the client has no id to change. The calls show Asha's list, then three requests that must fail.

Example 5 · src/main/java/com/shoplite/order/MyOrderController.java

Runs in: the shoplite-api Spring Boot project

Java
package com.shoplite.order;
import java.net.URI;
import org.springframework.http.ResponseEntity;import org.springframework.security.core.annotation.AuthenticationPrincipal;import org.springframework.security.oauth2.jwt.Jwt;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.shoplite.common.PageResponse;import com.shoplite.common.security.CurrentUser;
import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import jakarta.validation.Valid;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.Pattern;
/** * /api/v1/me/orders: the signed-in customer's own orders. The customer id comes from the token only, * so there is no id in the URL or the body that a client could change. */@Tag(name = "My orders", description = "The signed-in customer's own orders")@RestController@RequestMapping("/api/v1/me/orders")class MyOrderController {
    private final OrderService service;
    MyOrderController(OrderService service) {        this.service = service;    }
    @Operation(operationId = "listMyOrders", summary = "List my orders, newest first")    @GetMapping    PageResponse<OrderSummaryResponse> list(            @AuthenticationPrincipal Jwt jwt,            @RequestParam(required = false)            @Pattern(regexp = OrderController.STATUS_PATTERN, message = OrderController.STATUS_MESSAGE) String status,            @RequestParam(defaultValue = "0") @Min(value = 0, message = "must be 0 or more") int page,            @RequestParam(defaultValue = "20") @Min(value = 1, message = "must be between 1 and 100")            @Max(value = 100, message = "must be between 1 and 100") int size,            @RequestParam(defaultValue = "orderedAt,desc")            @Pattern(regexp = OrderController.SORT_PATTERN, message = OrderController.SORT_MESSAGE) String sort) {        Integer customerId = CurrentUser.from(jwt).requireCustomerId();        return service.search(customerId, status, sort, page, size);    }
    @Operation(operationId = "placeMyOrder", summary = "Place an order for myself")    @PostMapping    ResponseEntity<OrderResponse> place(@AuthenticationPrincipal Jwt jwt,                                        @Valid @RequestBody MyOrderRequest request) {        Integer customerId = CurrentUser.from(jwt).requireCustomerId();        OrderResponse placed = service.place(customerId, request.addressId(), request.items());        URI location = ServletUriComponentsBuilder.fromCurrentContextPath()                .path("/api/v1/orders/{id}").buildAndExpand(placed.id()).toUri();        return ResponseEntity.created(location).body(placed);    }}
Output
$ curl -i http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer $ASHA"
HTTP/1.1 200
Content-Type: application/json

{"content":[{"id":10,"customerId":1,"status":"DELIVERED","orderedAt":"2026-08-30T12:25:00+05:30","total":4398.00},{"id":3,"customerId":1,"status":"DELIVERED","orderedAt":"2026-07-18T13:05:00+05:30","total":43839.00},{"id":1,"customerId":1,"status":"DELIVERED","orderedAt":"2026-07-02T10:12:00+05:30","total":21097.00}],"page":0,"size":20,"totalElements":3,"totalPages":1}

$ curl -i -X POST http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer $ASHA" \
     -H "Content-Type: application/json" -d '{"addressId": 3, "items": [{"productId": 9, "quantity": 1}]}'
HTTP/1.1 422
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/rule-broken","title":"Business rule broken","status":422,"detail":"Address 3 does not belong to customer 1.","instance":"/api/v1/me/orders"}

$ curl -i -X POST http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer $ASHA" \
     -H "Content-Type: application/json" -d '{"customerId": 2, "addressId": 3, "items": [{"productId": 9, "quantity": 1}]}'
HTTP/1.1 400
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/malformed-request","title":"Malformed request","status":400,"detail":"The request body is not valid JSON for this endpoint.","instance":"/api/v1/me/orders"}

$ curl -i -X POST http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer $ASHA" \
     -H "Content-Type: application/json" -d '{"addressId": 1, "items": [{"productId": 9, "quantity": 1}, {"productId": 6, "quantity": 2}]}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/orders/17
Content-Type: application/json

{"id":17,"customerId":1,"addressId":1,"status":"PLACED","orderedAt":"2026-10-16T13:50:27+05:30","items":[{"productId":6,"sku":"ACC-AD141","productName":"boAt Airdopes 141","quantity":2,"unitPrice":1199.00,"lineTotal":2398.00},{"productId":9,"sku":"BK-CLEAN","productName":"Clean Code","quantity":1,"unitPrice":499.00,"lineTotal":499.00}],"total":2897.00}

$ curl -i http://localhost:8080/api/v1/me/orders -H "Authorization: Bearer $ADMIN"
HTTP/1.1 403
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/me/orders"}

What this code does

  • Asha's list holds only her orders 10, 3 and 1, newest first. The customer id came from her token.
  • Address 3 is Ravi's: 422 "Address 3 does not belong to customer 1." A body with customerId is an unknown field: 400. A correct body creates order 17 for Asha, with prices from the products table.
  • The admin gets 403 from the URL rule /api/v1/me/** → hasRole("CUSTOMER"): an admin has no orders of their own.

Example 6 · src/test/java/com/shoplite/order/OrderOwnershipIT.java

Runs in: the shoplite-api Spring Boot project

Java
package com.shoplite.order;
import static org.assertj.core.api.Assertions.assertThat;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import java.util.List;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.http.HttpStatus;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.JwtRequestPostProcessor;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.web.servlet.assertj.MockMvcTester;
/** * One customer must never see another customer's orders. Real controllers, services and MySQL * (seed data: order 1 is Asha's, order 14 is Ravi's); only the token is made up by jwt(). */@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")class OrderOwnershipIT {
    @Autowired    private MockMvcTester mvc;
    private static JwtRequestPostProcessor customer(int userId, int customerId) {        return jwt().jwt(token -> token.subject(String.valueOf(userId))                        .claim("roles", List.of("CUSTOMER")).claim("customerId", customerId))                .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER"));    }
    private static final JwtRequestPostProcessor ASHA = customer(2, 1);    private static final JwtRequestPostProcessor RAVI = customer(3, 2);    private static final JwtRequestPostProcessor ADMIN = jwt()            .jwt(token -> token.subject("1").claim("roles", List.of("ADMIN")))            .authorities(new SimpleGrantedAuthority("ROLE_ADMIN"));
    @Test    void customerReadsTheirOwnOrder() {        assertThat(mvc.get().uri("/api/v1/orders/1").with(ASHA))                .hasStatusOk()                .bodyJson().extractingPath("$.customerId").isEqualTo(1);    }
    @Test    void anotherCustomersOrderLooksExactlyLikeAMissingOrder() {        assertThat(mvc.get().uri("/api/v1/orders/14").with(ASHA))                .hasStatus(HttpStatus.NOT_FOUND)                .bodyJson().extractingPath("$.detail").isEqualTo("Order 14 was not found.");        assertThat(mvc.get().uri("/api/v1/orders/999").with(ASHA))                .hasStatus(HttpStatus.NOT_FOUND)                .bodyJson().extractingPath("$.detail").isEqualTo("Order 999 was not found.");    }
    @Test    void itemsAndCancelFollowTheSameRule() {        assertThat(mvc.get().uri("/api/v1/orders/14/items").with(ASHA)).hasStatus(HttpStatus.NOT_FOUND);        assertThat(mvc.post().uri("/api/v1/orders/14/cancel").with(ASHA)).hasStatus(HttpStatus.NOT_FOUND);    }
    @Test    void theOwnerAndAnAdminCanReadIt() {        assertThat(mvc.get().uri("/api/v1/orders/14").with(RAVI)).hasStatusOk();        assertThat(mvc.get().uri("/api/v1/orders/14").with(ADMIN)).hasStatusOk();    }
    @Test    void myOrdersHoldOnlyMyOrders() {        assertThat(mvc.get().uri("/api/v1/me/orders").with(ASHA))                .hasStatusOk()                .bodyJson().extractingPath("$.content[*].id").asArray().containsExactly(10, 3, 1);    }}
Sample output
$ ./mvnw verify          # TEST_DB_URL points to an empty test database; Flyway fills it
...
[INFO] Running com.shoplite.order.OrderOwnershipIT
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.094 s -- in com.shoplite.order.OrderOwnershipIT
...
[INFO] BUILD SUCCESS

What this code does

  • @SpringBootTest starts the whole app against a test database with the seed rows; only the token is made up, with jwt() and the claims ShopLite reads.
  • The key test compares Ravi's order 14 with a missing order 999: both must be 404 with the same detail. That is the negative test every owned resource needs.
  • myOrdersHoldOnlyMyOrders checks the exact ids 10, 3, 1, so a missing filter (all 16 orders) would fail the test.

MyOrderRequest has no customerId field at all. ShopLite rejects unknown fields, so a body that sends "customerId": 2 gets 400 instead of silently placing an order for Ravi. The address must still belong to the caller: address 3 is Ravi's, so the answer is 422.

The URL rule /api/v1/me/** needs ROLE_CUSTOMER, so the admin gets 403. The test class that follows proves all of this with real controllers, services and MySQL, and only a made-up token from jwt().

Customers still use /api/v1/orders/{id} for one order, because the Location header of a new order points there; the owner check makes that safe. The list GET /api/v1/orders stays admin-only.

Next step

Check your understanding

12 quick questions