Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A penetration test shows that changing the id in GET /api/invoices/123 returns another customer's invoice (IDOR). How do you fix it in this service and prevent it in others?

The endpoint has a URL rule that confirms the user is authenticated, but no object-level check that the invoice belongs to them, so any logged-in customer can read any invoice by changing the id. We fix it by checking ownership in the query, findByIdAndCustomerId, or with @PostAuthorize("returnObject.customerId == authentication.name"), and we centralise such checks with a PermissionEvaluator and hasPermission(). To prevent it elsewhere, we add tests that call every endpoint with another user's ids; random ids make guessing harder but never replace authorization.

Why this question is asked

IDOR, short for insecure direct object reference, is the most common serious finding in API penetration tests, and it is a form of broken object level authorization. It is also embarrassingly simple to exploit: log in, look at your own invoice URL, add one to the number. Interviewers ask this scenario because the fix for one endpoint is easy, while the fix for the organisation is the real question. In this answer, we will reproduce the problem, see why the existing security did not catch it, fix the service in three ways, add the tests that prevent it in other services, and discuss random ids.

1Reproducing the Problem

Here is a controller that looks perfectly normal and has the bug.

Java
http.authorizeHttpRequests(a -> a
.requestMatchers("/api/**").authenticated() // the only rule
.anyRequest().denyAll());
@GetMapping("/api/invoices/{id}")
InvoiceDto get(@PathVariable long id) {
return mapper.toDto(invoices.findById(id).orElseThrow(NotFound::new));
}
// alice (customer c-100) -> GET /api/invoices/123 -> 200, her invoice
// alice -> GET /api/invoices/124 -> 200, bob's invoice (customer c-200)
Step throughAn IDOR attack on /api/invoices
AliceFilter chainControllerDatabase
GET /api/invoices/124
authenticated? yes
pass
SELECT ... WHERE id = 124
bob's invoice
200 with bob's data

6 messages in order. Play them, or step through them one at a time.

Every step works as written. The missing step is the ownership check.

Notice what the URL rule checks: that a valid user is logged in. It has no way to know who owns invoice 124, because that information is in the database, not in the request. The controller then loads by id alone. Nothing between the request and the data ever asks whether this user may see this object.

2Fix 1: Put Ownership Into the Query

The most robust fix makes the database return only the caller's invoices.

Java
interface InvoiceRepository extends JpaRepository<Invoice, Long> {
Optional<Invoice> findByIdAndCustomerId(long id, String customerId);
}
@GetMapping("/api/invoices/{id}")
InvoiceDto get(@PathVariable long id, Authentication auth) {
return invoices.findByIdAndCustomerId(id, auth.getName())
.map(mapper::toDto)
.orElseThrow(NotFound::new);
}
// alice -> GET /api/invoices/123 -> 200
// alice -> GET /api/invoices/124 -> 404, as if it did not exist

Answering 404 rather than 403 means an attacker cannot even learn which invoice ids exist. And because the filter is in the query, the same approach protects list endpoints, exports and search, where loading first and checking afterwards would be slow or forgotten. The customer id comes from the authenticated principal, never from a request parameter.

3Fix 2: @PostAuthorize on the Service

When the service method is shared by several callers and we want the rule declared on it, @PostAuthorize checks the loaded object before returning it.

Java
@PostAuthorize("returnObject.customerId == authentication.name or hasRole('SUPPORT')")
public Invoice getInvoice(long id) {
return invoices.findById(id).orElseThrow(NotFound::new);
}
// alice -> getInvoice(124) -> query runs, check fails -> AccessDeniedException -> 403

This is easy to add to existing code, but notice two weaker points: the query runs before the check, and the result is a 403, revealing that the invoice exists, unless we map that exception to 404 for this resource. It suits single-object reads; for lists, the query filter is better.

4Fix 3: Centralise With a PermissionEvaluator

When many endpoints need similar ownership rules, copying expressions invites mistakes. A PermissionEvaluator keeps the rules for each domain type in one class, and services declare intent with hasPermission().

Java
@PreAuthorize("hasPermission(#id, 'Invoice', 'read')")
public Invoice getInvoice(long id) { ... }
// AppPermissionEvaluator, for type "Invoice":
// load the invoice by id; allow if invoice.customerId equals auth.getName() or user has ROLE_SUPPORT;
// deny for any unknown type or permission

The rule for reading an invoice now has one definition and its own unit tests, and a reviewer can check that every invoice method carries a hasPermission annotation. In practice we combine fixes: query filters for lists and searches, and a central evaluator or annotation for single-object operations, especially writes such as cancel and refund.

5Preventing It in Other Services

Fixing one endpoint does not tell us how many others share the bug. So the prevention is a test pattern every service adopts: create data for two users, then call each endpoint as user B with user A's ids and expect 404 or 403.

Java
@ParameterizedTest
@MethodSource("objectEndpoints") // e.g. GET /api/invoices/{id}, POST /api/invoices/{id}/refund
void otherCustomersObjectsAreInvisible(HttpMethod method, String template) throws Exception {
long aliceInvoice = fixtures.invoiceFor("alice");
mvc.perform(request(method, template, aliceInvoice).with(user("bob")))
.andExpect(status().isNotFound()); // fails today for GET /api/invoices/{id}
}

To make it hard to skip, the list of object endpoints can be generated from the handler mappings, and a new endpoint with a path variable fails the build until it is added. Security reviews and penetration tests then look for the remaining cases, and every real finding becomes a new test. Teams also benefit from a short code review rule: any repository call that loads by id alone in a user-facing path needs a reason.

6What Random Ids Do and Do Not Do

Switching from sequential numbers to random UUIDs makes enumeration impractical: an attacker cannot simply add one. That is a good extra layer, and it also hides business volumes such as how many invoices we issue per day. But it is not authorization. Ids leak in URLs shared by email, browser history, logs, referrer headers and support tickets, and anyone who obtains one would still get the invoice. So random ids reduce guessing, while ownership checks are what actually protect the data.

7Follow-up questions

Why did the penetration testers find this when our tests passed?

Most functional tests call endpoints as the owner of the data, so they always succeed. Penetration testers deliberately use two accounts and swap ids. Our tests must do the same, which is why the two-user test pattern is the core of prevention.

Should the fix go in the controller or the service?

In the service or the query. Controllers are one entry point among several; a message listener or a batch job may call the same service. Putting the rule close to the data means every path gets it.

How do support staff read any invoice after the fix?

Through an explicit permission such as ROLE_SUPPORT in the rule, or through a separate support endpoint, and every such access is audit logged. The important thing is that the exception is written deliberately, not left open for everyone.

8Conclusion

In this answer, we reproduced an IDOR where the URL rule only checked authentication and the controller loaded invoices by id alone. We fixed it by filtering the query by the authenticated customer and returning 404, showed @PostAuthorize for shared service methods and a PermissionEvaluator for centralised rules, prevented repeats with two-user tests across every object endpoint, and saw that random ids reduce guessing but do not replace authorization.

What to say in the interviewAbout 80 seconds aloud

Open with

The root cause is that the only rule is at the URL level, which checks that the user is authenticated, while the controller loads the invoice by id without checking that it belongs to the caller.

Then, if they want more

To fix this service, I would put ownership into the query, findByIdAndCustomerId with the customer id from the authenticated principal, and return 404 when nothing comes back, so we do not even reveal that the invoice exists. That also protects list and search endpoints.

Where a service method is shared, @PostAuthorize with returnObject.customerId == authentication.name, plus a support role exception, works for single reads, and for many domain types I would centralise the rules in a PermissionEvaluator so methods just say hasPermission(#id, 'Invoice', 'read').

To prevent it in other services, I would introduce a standard test: create data for two users and call every endpoint that takes an object id as the other user, expecting 404 or 403, with the endpoint list generated from the handler mappings so new endpoints cannot skip it.

I would also mention that switching to random UUIDs is a good extra layer against enumeration, but ids leak in links and logs, so it never replaces the ownership check.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A penetration test shows that changing the id in GET /api/invoices/123 returns another...": https://scrivio-interview-library.netlify.app/spring-boot/authorization/f4e55ba1f2/