Insecure Direct Object Reference with Bearer Tokens
How Insecure Direct Object Reference Manifests in Bearer Tokens
In Bearer Tokens, Insecure Direct Object Reference (IDOR) vulnerabilities occur when token-based authentication fails to properly validate whether the authenticated user has permission to access specific resources. This manifests in several critical ways:
// Vulnerable: Directly using token data without authorization check
app.get('/api/users/:userId', (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// IDOR vulnerability: assuming userId in token matches requested resource
if (decoded.userId === req.params.userId) {
return res.json(users.find(u => u.id === req.params.userId));
}
res.status(403).json({ error: 'Forbidden' });
});
The above code assumes that if the token's userId matches the requested userId, access is granted. However, this fails when:
- An attacker modifies the token to change userId
- A user with a valid token accesses another user's data by changing the URL parameter
- Token scopes are improperly validated against resource ownership
Another common Bearer Tokens IDOR pattern:
// Vulnerable: Blind IDOR via token scopes
app.get('/api/documents/:docId', (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// IDOR: No check if user owns this document
const doc = documents.find(d => d.id === req.params.docId);
res.json(doc);
});
Here, the endpoint trusts that any valid token can access any document, completely bypassing authorization checks. The vulnerability becomes exploitable when:
- Tokens contain insufficient scope information
- Resource ownership isn't validated against token claims
- Database queries don't filter by user ID
Real-world examples include GitHub's 2014 IDOR vulnerability where authenticated users could access private repositories by guessing repository IDs, and Facebook's 2018 bug allowing access to private photos via direct URL manipulation.
Bearer Tokens-Specific Detection
Detecting IDOR in Bearer Tokens requires systematic testing that goes beyond basic authentication. middleBrick's black-box scanning approach tests the unauthenticated attack surface by manipulating token claims and observing system responses:
# Using middleBrick CLI to scan for IDOR vulnerabilities
middlebrick scan https://api.example.com --auth-bearer "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
middleBrick specifically tests Bearer Tokens IDOR by:
- Modifying token claims (userId, role, permissions) and observing access changes
- Testing sequential resource IDs to detect predictable patterns
- Checking if token scopes properly restrict access to owned resources
- Verifying that resource ownership validation exists for all endpoints
Manual detection techniques for Bearer Tokens IDOR:
// Test for IDOR by swapping tokens
const userA = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
const userB = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
// Try accessing userA's data with userB's token
fetch('/api/users/123', {
headers: { Authorization: `Bearer ${userB}` }
}).then(res => {
if (res.status === 200) {
console.log('IDOR vulnerability: userB accessed userA\'s data');
}
});
Key detection indicators:
| Indicator | What to Look For | Security Impact |
|---|---|---|
| Token Claim Manipulation | Changing userId in token grants access to different resources | Critical |
| Sequential ID Access | Modifying numeric IDs in URLs returns different users' data | High |
| Missing Ownership Validation | Endpoints return data without checking if requester owns it | Critical |
| Scope Bypass | Valid tokens access resources outside their intended scope | High |
middleBrick's API scanning reports provide severity scores and specific findings for each endpoint tested, mapping directly to OWASP API Top 10 IDOR (A4) violations.
Bearer Tokens-Specific Remediation
Remediating IDOR in Bearer Tokens requires implementing proper authorization checks that validate resource ownership regardless of token validity. The core principle: always verify that the authenticated user has permission to access the specific resource requested.
// Secure: Proper authorization with resource ownership validation
app.get('/api/users/:userId', async (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Verify user exists and owns this resource
const user = await User.findById(decoded.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Check if user owns the requested resource
if (user.id !== parseInt(req.params.userId)) {
return res.status(403).json({ error: 'Forbidden: Not your resource' });
}
res.json(user);
});
For multi-tenant applications, implement tenant-based authorization:
// Secure: Multi-tenant authorization
app.get('/api/organizations/:orgId/projects', async (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Verify user belongs to organization
const user = await User.findById(decoded.userId);
const org = await Organization.findById(req.params.orgId);
if (!org || !user.organizations.includes(org.id)) {
return res.status(403).json({ error: 'Forbidden: Not your organization' });
}
const projects = await Project.find({ organization: org.id });
res.json(projects);
});
Database-level authorization using token claims:
// Secure: Database query with authorization
app.get('/api/documents/:docId', async (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const doc = await Document.findOne({
_id: req.params.docId,
owner: decoded.userId
});
if (!doc) {
return res.status(404).json({ error: 'Document not found or access denied' });
}
res.json(doc);
});
Best practices for Bearer Tokens IDOR prevention:
- Never trust token claims for authorization decisions
- Always validate resource ownership on the server
- Use database-level authorization filters
- Implement proper role-based access control (RBAC)
- Test with multiple user accounts to verify isolation
middleBrick's remediation guidance maps findings to specific code fixes and provides severity-based recommendations for addressing IDOR vulnerabilities in your Bearer Tokens implementation.
Related CWEs: bolaAuthorization
| CWE ID | Name | Severity |
|---|---|---|
| CWE-250 | Execution with Unnecessary Privileges | HIGH |
| CWE-639 | Insecure Direct Object Reference | CRITICAL |
| CWE-732 | Incorrect Permission Assignment | HIGH |
Frequently Asked Questions
How can I test if my Bearer Tokens API has IDOR vulnerabilities?
middlebrick scan https://api.example.com --auth-bearer "your-token-here". The scanner tests token claim manipulation, sequential ID access, and missing ownership validation. For manual testing, try accessing resources using different user tokens or modifying token claims to see if you can access unauthorized data.