Skip to content

Broken object-level authorization (IDOR)

When is it relevant

A new or changed entry point that takes a resource identifier (path parameter, query, body, or a nested or bulk list of IDs) and reads, changes or deletes that resource or its children.

Attack

The attacker replaces the ID with one that belongs to someone else, and the server acts on it because it only checks that the caller is logged in. IDs hidden in the body, child resources checked only through their parent, and "unguessable" UUIDs that leak through other responses are all easy to miss.

Mitigation

  • Load the resource scoped to the caller (WHERE id = ? AND owner_id = ?), or check ownership after loading and before acting.
  • Check every ID in the request, including IDs in the body and IDs of child resources.
  • Return the same 404 for "doesn't exist" and "not yours".
  • Don't rely on IDs being hard to guess.

Test

  • Point-in-time: with two users, have user B request, change and delete user A's resource by its ID, including IDs in the body and child IDs. Each must fail with the same 404 as a missing record.
  • Continuous: a two-user integration test per resource route, kept in CI. Add a test row whenever a route that takes an ID is added.

Examples

Mitigation options

Option When it fits Docs
Scope the query (WHERE owner_id = ?) Default choice; the check can't be forgotten later node-postgres, Mongoose queries
Load then check in the handler You need the record anyway, or the rule is more than ownership Express routing
Check in the data-access layer Many handlers share one repository function CASL

Vulnerable — authenticated, but not authorised

router.delete('/documents/:id', requireAuth, async (req, res) => {
  await db.query('DELETE FROM documents WHERE id = $1', [req.params.id])
  res.sendStatus(204)
})

Vulnerable — child object checked through its parent only

router.get('/projects/:projectId/tasks/:taskId', requireAuth, async (req, res) => {
  const project = await Project.findOne({ _id: req.params.projectId, ownerId: req.user.id })
  if (!project) return res.sendStatus(404)
  res.json(await Task.findById(req.params.taskId))   // taskId never tied to project
})

Mitigated — scope the query

router.delete('/documents/:id', requireAuth, async (req, res) => {
  const { rowCount } = await db.query(
    'DELETE FROM documents WHERE id = $1 AND owner_id = $2',
    [req.params.id, req.user.id],
  )
  if (rowCount === 0) return res.sendStatus(404)
  res.sendStatus(204)
})

The same 404 covers "doesn't exist" and "not yours", so the response doesn't confirm that someone else's ID is real.

Docs: node-postgres parameterised queries

Mitigated — load then check

const doc = await Document.findById(req.params.id)
if (!doc) return res.sendStatus(404)
if (String(doc.ownerId) !== String(req.user.id)) return res.sendStatus(404)
await doc.deleteOne()

Docs: Mongoose queries

Mitigated — data-access layer

// repositories/documents.js — handlers cannot reach the model directly
export function forUser(user) {
  return {
    find: (id) => Document.findOne({ _id: id, ownerId: user.id }),
    remove: (id) => Document.deleteOne({ _id: id, ownerId: user.id }),
  }
}

Bypasses to check

  • Check one ID, act on another. Ownership verified for req.params.id while the write uses req.body.id, or a bulk route (ids: []) that checks only the first element.
  • Nested and related IDs: child resources, populate()/JOIN targets, attachments, and "duplicate"/"export"/"share" routes reached from an object you do own.
  • Ownership compared with == across types (ObjectId vs string), or doc.ownerId === req.user.id where one side is an object — always false or always true rather than a real comparison.
  • The owner column taken from the request (req.body.ownerId) instead of the session.
  • Read path scoped but the write path not, or vice versa.
  • Check then change: the record is re-fetched without the scope after the check, or the ID is re-parsed (parseInt, trim) between check and use.
  • findByIdAndUpdate(req.params.id, ...) with the ownership filter omitted because "the UI only shows your own documents".

What to grep for

  • findById(, findByIdAndUpdate(, findByIdAndDelete(, deleteOne(
  • req.params.id, req.body.id, req.query.id
  • WHERE id =, { _id: without an owner or tenant field alongside

Mitigation options

Option When it fits Docs
Scoped repository query (findByIdAndOwnerId) Default choice; the check can't be forgotten later Spring Data query methods
Load then check in the service You need the record anyway, or the rule is more than ownership Spring Data CrudRepository
@PreAuthorize / @PostAuthorize with a bean Rules shared across controllers, expressed once Method security

The examples use Spring Data repositories. The same applies to MongoTemplate and JdbcTemplate: the owner or parent ID has to be in the query or checked after it.

Vulnerable — authenticated, but not authorised

@DeleteMapping("/api/documents/{id}")
public void delete(@PathVariable Long id) {
    documents.deleteById(id);                   // any logged-in user, any document
}

Vulnerable — child object checked through its parent only

@GetMapping("/api/projects/{projectId}/tasks/{taskId}")
public Task get(@PathVariable String projectId, @PathVariable String taskId) {
    projects.getForMember(projectId, CurrentUser.id());     // caller is in this project
    return tasks.findById(taskId).orElseThrow();            // but the task can be from any project
}

The guard passes for the caller's own project, and taskId comes from someone else's.

Vulnerable — the ID in the body wins

@PutMapping("/api/documents/{id}")
public Document update(@PathVariable Long id, @RequestBody Document body) {
    Document doc = documents.findByIdAndOwnerId(id, currentUserId()).orElseThrow(NotFound::new);
    return documents.save(body);                // body.id (and body.ownerId) decide what is written
}

Mitigated — scope the query

interface DocumentRepository extends JpaRepository<Document, Long> {
    Optional<Document> findByIdAndOwnerId(Long id, Long ownerId);
    long deleteByIdAndOwnerId(Long id, Long ownerId);
}

@DeleteMapping("/api/documents/{id}")
@Transactional
public ResponseEntity<Void> delete(@PathVariable Long id, @AuthenticationPrincipal AppUser me) {
    return documents.deleteByIdAndOwnerId(id, me.getId()) == 0
            ? ResponseEntity.notFound().build()           // same 404 for "not yours"
            : ResponseEntity.noContent().build();
}

Docs: Derived query methods · @AuthenticationPrincipal

Mitigated — tie the child to its parent

private Task requireTaskInProject(String projectId, String taskId) {
    return tasks.findByIdAndProjectId(taskId, projectId)
            .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "Task not found"));
}

Check the parent (membership), then load the child with the parent's ID, on read, update and delete alike. Load-then-compare (task.getProjectId().equals(projectId)) works too if every path does it.

Docs: Spring Data MongoDB query methods

Mitigated — method security with a bean

@PostAuthorize("returnObject.ownerId == authentication.principal.id")
public Document get(Long id) {
    return documents.findById(id).orElseThrow(NotFound::new);
}

@PostAuthorize runs after the method, so use it only on reads: a write would already have happened. For writes, use @PreAuthorize("@docAccess.canEdit(#id, authentication)"). Both need @EnableMethodSecurity.

Docs: @PostAuthorize

Bypasses to check

  • Check one ID, act on another. Ownership checked for the path ID, then save(body) writes body.id; or a bulk endpoint (List<Long> ids) that checks only the first element.
  • findById, getReferenceById, existsById, deleteById from CrudRepository used directly in a controller or service with no owner or parent filter.
  • Child resources: tasks, comments, attachments looked up by their own ID after the parent was checked; @DBRef / JPA relations followed from an object the caller owns to one they don't.
  • Spring Data REST (@RepositoryRestResource) exposing /documents/{id} with no ownership rule at all.
  • Comparing IDs with == on Long or String objects instead of equals: Long values above 127 aren't cached, so the check fails for some IDs and someone "fixes" it by removing it.
  • Read path scoped but the write path not, or the reverse; a server-rendered controller and a JSON controller calling different service methods.
  • @PostAuthorize on a method that modifies data.
  • Different responses for "doesn't exist" (404) and "not yours" (403), which confirms other users' IDs.

What to grep for

  • findById(, getReferenceById(, deleteById(, existsById(, save( with a request body
  • mongo.findById(, mongoTemplate.findById(, Query.query(where("_id")
  • @PathVariable IDs and @RequestBody entities in the same method
  • @PostAuthorize, @PreAuthorize, @RepositoryRestResource

Vulnerable

@login_required
def delete_document(request, pk):
    Document.objects.filter(pk=pk).delete()
    return HttpResponse(status=204)

Mitigated

@login_required
def delete_document(request, pk):
    document = get_object_or_404(Document, pk=pk, owner=request.user)
    document.delete()
    return HttpResponse(status=204)

get_object_or_404 raises the same 404 whether the document belongs to someone else or doesn't exist.

Vulnerable

def destroy
  Document.find(params[:id]).destroy
  head :no_content
end

Mitigated

def destroy
  current_user.documents.find(params[:id]).destroy
  head :no_content
end

Scoping through the association means find raises RecordNotFound, which Rails renders as 404, for documents owned by anyone else.

Mitigation options

Option When it fits Docs
Scope the query by the caller ({'_id': id, 'owner_id': g.user['id']}) Default choice; there is no unscoped read to forget PyMongo find_one, SQLAlchemy where
One loader helper per resource that checks access and aborts Many routes share a parent (a project, a repository) flask.abort
A policy library (Flask-Principal, Oso, Casbin) Complex sharing rules Flask-Principal

Vulnerable — load by ID, no owner check

@app.get('/api/notes/<note_id>')
@login_required
def get_note(note_id):
    note = db.notes.find_one({'_id': ObjectId(note_id)})
    return jsonify(serialize(note)) if note else ('', 404)

Vulnerable — the parent is checked, the child is not

@app.get('/<owner>/<name>/issues/<int:number>')
def issue(owner, name, number):
    repo = load_repo(owner, name)                 # checks the caller can see this repo
    issue = db.issues.find_one({'number': number, 'repo_id': request.args.get('repo')})
    ...

The access check is for the repository in the URL, but the query uses a repo_id from the query string.

Mitigated — scoped query

@app.get('/api/notes/<note_id>')
@login_required
def get_note(note_id):
    oid = to_object_id(note_id)                   # None for invalid ids → 404, not 500
    note = oid and db.notes.find_one({'_id': oid, 'owner_id': g.user['id']})
    if not note:
        abort(404)
    return jsonify(serialize(note))

Docs: PyMongo find_one · bson.ObjectId.is_valid

Mitigated — one loader for a parent, child queries keyed by the loaded parent

def load_repo(owner, name, need='read'):
    repo = repos.find_by_owner_and_name(owner, name)
    if not repo or not can_view(repo, current_user_id()):
        abort(404)                                # private and missing look the same
    if need == 'write' and not can_write(repo, current_user_id()):
        abort(403)
    return repo

issue = db.issues.find_one({'repo_id': repo['id'], 'number': number})

Bypasses to check

  • Routes for the same object that use different loaders. The JSON API often has its own copy of the check.
  • A 404 for missing objects and a 403 for other users' objects. That tells the caller which IDs exist.
  • Child IDs taken from the body or query string instead of from the object that was loaded.
  • ObjectId(value) raising on bad input. It's a crash, not a check.
  • Bulk and list endpoints (?ids=, exports) that skip the per-object check.

What to grep for

  • find_one(, find(, update_one(, delete_one(, .query.get(, session.get(
  • <id>, <int:, request.args.get(, request.json, ObjectId(
  • abort(403), abort(404), owner_id, g.user

Resources