# 不安全的直接对象引用 (IDOR) 允许通过可预测的 ID 访问其他用户的数据

- **ID:** `security/insecure-direct-object-reference-in-api`
- **领域:** security
- **类别:** auth_error
- **错误码:** `AUTH_IDOR_006`
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

API 在 URL 或请求体中暴露内部对象 ID（例如用户 ID、订单号），而未验证经过身份验证的用户是否拥有该资源，从而允许未经授权访问其他用户的数据。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| REST API | active | — | — |
| GraphQL | active | — | — |
| Spring Boot 3.1 | active | — | — |

## 解决方案

1. ```
   Implement authorization checks on every API endpoint that accesses a resource by ID. Example in Node.js/Express:
app.get('/api/order/:id', async (req, res) => {
    const order = await Order.findById(req.params.id);
    if (!order || order.userId !== req.user.id) {
        return res.status(403).json({ error: 'Forbidden' });
    }
    res.json(order);
});
   ```
2. ```
   Use attribute-based access control (ABAC) with a policy engine (e.g., OPA) to centrally enforce that users can only access resources they own.
   ```
3. ```
   Replace direct object IDs with opaque, non-guessable tokens (e.g., signed JWTs) that encode the user's identity and resource ownership, and validate the signature on each request.
   ```

## 无效尝试

- **Obfuscate object IDs by using hashes (e.g., MD5) instead of sequential numbers** — Obfuscation is not authorization; if the hash is leaked or guessed (e.g., via enumeration), access is still granted. Authorization checks are required. (95% 失败率)
- **Use UUIDs instead of integers for IDs** — UUIDs make guessing harder but do not prevent access if a user obtains another user's UUID (e.g., via shared links or logs). Authorization is still missing. (90% 失败率)
