Missing ownership checks (IDOR)
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Asha is signed in and opens her order 14. She changes the 14 to 15 in the address bar and sees another customer's order. Her login was valid, so what was missing?
IDOR: changing an id to reach someone else's data
IDOR (insecure direct object reference) is an endpoint that takes an id from the request and returns or changes that object without checking that the caller may use it. The attacker only changes 14 to 15.
The mistake first: an order service that loads any order by id, and the requests that read and change orders that are not the caller's.
Example 1 · Mistake: OrderService loads the order without an owner check
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/order/OrderService.java (the mistake)public OrderResponse get(Integer id, CurrentUser caller) { Order order = orders.findWithItemsById(id) .orElseThrow(() -> new ResourceNotFoundException("Order", id)); return OrderMapper.toResponse(order, time); // caller is never looked at}# Asha (customer 1) asks for order 14, which belongs to Ravi (customer 2)$ curl -i http://localhost:8080/api/v1/orders/14 -H "Authorization: Bearer $ASHA"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
$ASHAholds the access token fromPOST /api/v1/auth/loginfor asha.rao@example.com (customer 1).- The role rule
hasAnyRole("CUSTOMER", "ADMIN")lets Asha in, and the service never comparescustomerId2 with her own customer id 1. - Ravi's order, address id and purchases are now Asha's to read, and by changing the number she can read every order in the shop.
Signing in does not prevent it. Asha has a valid token and the CUSTOMER role, so every role rule lets her through. The missing piece is the question "is order 14 hers?", and only the code that loads order 14 can answer it.
OWASP Top 10 2025 puts this under A01 Broken Access Control, the most common risk in real APIs. In ShopLite's threat model it is risk R3.
The fix: an owner check where the object is loaded
An owner check compares the owner stored with an object to the caller taken from the verified token. The caller comes only from the token, never from a path, query or body value.
The fixed OrderService: one private visibleTo method that every id-taking method calls.
Example 2 · src/main/java/com/shoplite/order/OrderService.java (the owner check)
Runs in: the shoplite-api Spring Boot project
/** One order, for its owner or an admin. Anyone else gets 404, as if the order did not exist. */public OrderResponse get(Integer id, CurrentUser caller) { return OrderMapper.toResponse(visibleTo(load(id), caller), time);}
/** The items of one order: a nested resource needs the same owner check as its parent. */public List<OrderItemResponse> items(Integer id, CurrentUser caller) { return OrderMapper.toResponse(visibleTo(load(id), caller), time).items();}
/** * The owner check. Every method that takes an order id from the URL goes through it. * 404 rather than 403: a stranger must not learn that order 14 exists. */private static Order visibleTo(Order order, CurrentUser caller) { if (!caller.canSee(order.getCustomer().getId())) { throw notFound(order.getId()); } return order;}
// src/main/java/com/shoplite/common/security/CurrentUser.javapublic boolean canSee(Integer ownerCustomerId) { return admin || (customerId != null && customerId.equals(ownerCustomerId));}$ 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 http://localhost:8080/api/v1/orders/99 -H "Authorization: Bearer $ASHA"
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 99 was not found.","instance":"/api/v1/orders/99"}What this code does
visibleTois the single place where ownership is decided;get,itemsandcancelall call it.- Order 14 (someone else's) and order 99 (missing) give the same 404 body, so Asha learns nothing about other customers.
CurrentUseris built from the token'scustomerIdandrolesclaims, so the caller cannot pretend to be someone else.
ShopLite puts the check in the service, where the object is loaded. A stranger gets 404, exactly like an order that does not exist, so the answer does not even confirm that order 14 is real. An admin passes the check for every order.
The controller only passes the token along. If the check lived in the controller, the next endpoint written by a teammate could forget it; in the service it is on the only road to the data.
Finding IDOR in a code review: reads, writes and nested resources
A nested resource is data reached through its parent in the URL, like /orders/14/items. It has no owner column of its own, so the code must check the parent order first.
Order 16 belongs to Divya. Asha tries to cancel it and to read its items, first without the check, then with it.
Example 3 · Mistake and fix: cancelling and reading items of another customer's order
Runs in: the shoplite-api Spring Boot project
# Order 16 belongs to Divya (customer 7) and is still PLACED# With the mistake (no owner check):$ curl -X POST http://localhost:8080/api/v1/orders/16/cancel -H "Authorization: Bearer $ASHA"# With the owner check:$ curl -X POST http://localhost:8080/api/v1/orders/16/cancel -H "Authorization: Bearer $ASHA"$ curl http://localhost:8080/api/v1/orders/14/items -H "Authorization: Bearer $ASHA"With the mistake:
{"id":16,"customerId":7,"addressId":9,"status":"CANCELLED","orderedAt":"2026-09-29T16:30:00+05:30","items":[{"productId":13,"sku":"FSH-SHOE","productName":"Running Shoes","quantity":1,"unitPrice":2499.00,"lineTotal":2499.00},{"productId":11,"sku":"BK-ATOMIC","productName":"Atomic Habits","quantity":3,"unitPrice":399.00,"lineTotal":1197.00}],"total":3696.00}
With the owner check:
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Order 16 was not found.","instance":"/api/v1/orders/16/cancel"}
{"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
- Without the check, Asha cancelled Divya's order: a write, not just a leak, and the stock was put back.
- In the fixed
cancel,visibleToruns right after the order row is loaded and locked, before any change. - The nested
itemsendpoint answers 404 too, because it checks the parent order first.
Review with one rule: every endpoint that takes an id needs an answer to "whose is it, and who checks?". Look for ids in four places:
- Path ids:
/orders/{id},/orders/{id}/items,/orders/{id}/cancel. - Body ids:
addressId,productId,customerIdin a request record. - Query ids:
?customerId=2on a list endpoint. - For each one: an owner check in the service, an admin-only URL rule, or public data on purpose.
A customerId in a body is the worst kind: the server must take it from the token instead, which is why /me/... URLs exist. Check writes as hard as reads: a missing check on cancel lets a stranger change an order, not just see it. ShopLite's items(id, caller) runs the same visibleTo check as get.
Find the bug
Find the missing owner check
Tap the line that lets a stranger through, then read the fix.
This service method returns an order by id. Which line is the bug?
Round 1 of 3Guessable ids, and why random ids alone are not a fix
Counter ids against random ids: what one id tells an attacker, and why a random id is still not a permission.
Example 4 · Sequential ids are easy to guess; random ones are not a permission
import java.util.List;import java.util.UUID;
public class GuessableIdsDemo { public static void main(String[] args) { int myOrder = 14; List<Integer> neighbours = List.of(myOrder - 1, myOrder + 1, myOrder + 2); System.out.println("My order: " + myOrder + ", ids worth trying: " + neighbours);
UUID random = UUID.randomUUID(); System.out.println("UUID length: " + random.toString().length() + " characters"); System.out.println("UUID version: " + random.version());
// A shared link gives the id away, however random it is String sharedLink = "https://shop.example/orders/" + random; String leakedId = sharedLink.substring(sharedLink.lastIndexOf('/') + 1); System.out.println("Id read from a shared link matches: " + leakedId.equals(random.toString())); }}My order: 14, ids worth trying: [13, 15, 16] UUID length: 36 characters UUID version: 4 Id read from a shared link matches: true
What this code does
- Counter ids tell anyone who sees one id where the others are.
UUID.randomUUID()(version 4) has 122 random bits, so guessing is not practical.- But a random id that appears in a link, a screenshot or a log is known to whoever sees it, so the server must still check ownership.
ShopLite's ids are AUTO_INCREMENT numbers, so they are guessable: after order 14 comes 15. Random ids such as UUIDs are much harder to guess, which reduces how easily a bug is found.
Random ids do not fix the bug. Ids travel in shared links, screenshots, browser history, e-mails and logs, and an ex-employee or a curious support agent may know them. Treat a random id as a small extra layer; the owner check is still required on every endpoint.
A negative test for every owned resource
A negative test checks that something is refused, such as "customer A cannot read customer B's order". Normal tests only prove that owners can use their data; they pass happily when strangers can too.
An integration test that signs in as Asha and tries to read, list and cancel other customers' orders.
Example 5 · src/test/java/com/shoplite/order/OrderOwnershipIT.java
Runs in: the shoplite-api Spring Boot project with the shoplite_test database
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.jdbc.core.simple.JdbcClient;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.jdbc.Sql;import org.springframework.test.web.servlet.assertj.MockMvcTester;import org.springframework.test.web.servlet.request.RequestPostProcessor;
/** A customer must never reach another customer's order: not by reading, not through items, not by cancelling. */@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)class OrderOwnershipIT {
@Autowired private MockMvcTester mvc;
@Autowired private JdbcClient jdbc;
/** Asha (customer 1), signed in with the claims ShopLite's tokens carry. */ private static final RequestPostProcessor ASHA = jwt() .jwt(token -> token.subject("2").claim("customerId", 1) .claim("roles", List.of("CUSTOMER"))) .authorities(new SimpleGrantedAuthority("ROLE_CUSTOMER"));
@Test void ownerReadsOwnOrder() { assertThat(mvc.get().uri("/api/v1/orders/1").with(ASHA)).hasStatusOk(); }
@Test void otherCustomersOrderIs404() { assertThat(mvc.get().uri("/api/v1/orders/14").with(ASHA)) .hasStatus(HttpStatus.NOT_FOUND) .bodyJson().extractingPath("$.detail").isEqualTo("Order 14 was not found."); }
@Test void otherCustomersOrderItemsAre404() { assertThat(mvc.get().uri("/api/v1/orders/14/items").with(ASHA)).hasStatus(HttpStatus.NOT_FOUND); }
@Test void cannotCancelOtherCustomersOrder() { assertThat(mvc.post().uri("/api/v1/orders/16/cancel").with(ASHA)).hasStatus(HttpStatus.NOT_FOUND); String status = jdbc.sql("SELECT status FROM orders WHERE order_id = 16").query(String.class).single(); assertThat(status).isEqualTo("PLACED"); // nothing changed in the database }
@Test void customerCannotShip() { assertThat(mvc.post().uri("/api/v1/orders/15/ship").with(ASHA)).hasStatus(HttpStatus.FORBIDDEN); }
@Test void noTokenIs401() { assertThat(mvc.get().uri("/api/v1/orders/14")).hasStatus(HttpStatus.UNAUTHORIZED); }
// In the project: also adminReadsAnyOrder and missingAndForeignOrdersLookTheSame}$ mvn verify -Dit.test=OrderOwnershipIT ... [INFO] Running com.shoplite.order.OrderOwnershipIT [INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 31.13 s -- in com.shoplite.order.OrderOwnershipIT [INFO] [INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
What this code does
jwt()signs a test request in with the same claims as a real token, so no login call or real key is needed.- Each test names one refusal;
cannotCancelOtherCustomersOrderalso reads the row to prove nothing changed. - The run shows 8 tests because the project class has two more (admin access and missing-equals-foreign); remove the owner check and the 404 tests fail at once.
Write at least one negative test for every owned resource: read, change and list. Spring Security's test support makes this cheap: jwt() from SecurityMockMvcRequestPostProcessors signs a test request in with any claims you choose, without a real login.
For a change such as cancel, also check the database afterwards: the status must still be PLACED.
Next step
Check your understanding
12 quick questions