Nosql Injection with Bearer Tokens
How Nosql Injection Manifests in Bearer Tokens
Nosql injection in Bearer Tokens contexts typically occurs when token payloads are used to construct database queries without proper sanitization. This vulnerability allows attackers to manipulate token claims or embedded data to execute unintended database operations.
Consider a scenario where a Bearer Token contains a user ID claim that's directly injected into a MongoDB query:
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.decode(token, { complete: true });
const userId = decoded.payload.userId;
// Vulnerable query construction
const user = await db.collection('users').findOne({ _id: userId });An attacker can craft a token with a malicious userId value like { "$ne": null }, which translates to a query matching all documents where _id is not equal to null—effectively bypassing authentication and retrieving all user data.
More sophisticated attacks exploit MongoDB's query operators. A token containing { "$where": "this.admin === true" } can force the database to execute arbitrary JavaScript code during query evaluation, potentially escalating privileges or extracting sensitive data.
Another common pattern involves using Bearer Tokens to specify database collection names or filter parameters. If an API endpoint accepts a token claim that determines which collection to query, an attacker might manipulate this to access unauthorized data sources:
// Vulnerable: collection name from token claim
const collectionName = decoded.payload.collection;
const results = await db.collection(collectionName).find({});This allows access to any collection the database user has permissions for, including system collections containing sensitive metadata.
Bearer Tokens-Specific Detection
Detecting Nosql injection in Bearer Token implementations requires both static analysis and runtime testing. The most effective approach combines automated scanning with manual code review.
middleBrick's black-box scanning methodology specifically tests for Nosql injection by injecting payloads through the authentication layer. The scanner attempts to manipulate token claims with known dangerous patterns:
// middleBrick's injection test patterns
const injectionPayloads = [
{ "$ne": null },
{ "$where": "this.admin === true" },
{ "$gt": "" },
{ "$exists": true },
{ "$regex": ".*" }
The scanner monitors responses for indicators of successful injection, such as unexpected data volumes, authentication bypass, or error messages revealing database structure.
For development teams, static analysis tools can identify vulnerable patterns in Bearer Token handling code. Look for these red flags:
- Direct use of token claims in database queries without validation
- Dynamic collection name construction from token data
- Unsanitized JSON objects passed to query builders
- Missing type checking on token-derived parameters
Runtime detection involves monitoring database query logs for suspicious patterns. Queries with operators like $where, $regex with wildcards, or $ne comparisons on indexed fields may indicate injection attempts.
middleBrick's API security scanning provides comprehensive coverage by testing the actual authentication flow. Unlike static analysis tools, it validates whether the vulnerability is exploitable in production, saving developers from chasing theoretical issues.
Bearer Tokens-Specific Remediation
Remediating Nosql injection in Bearer Token implementations requires a defense-in-depth approach. The most effective strategy combines input validation, parameterized queries, and principle of least privilege.
First, validate token claims against strict schemas before using them in queries:
const Joi = require('joi');
const userIdSchema = Joi.string().alphanum().length(24); // MongoDB ObjectID format
const collectionSchema = Joi.string().valid('users', 'orders', 'products');
function validateTokenClaims(claims) {
const { error } = Joi.object({
userId: userIdSchema,
collection: collectionSchema,
role: Joi.string().valid('user', 'admin')
if (error) throw new Error('Invalid token claims');
return claims;
}Second, use parameterized queries or query builders that automatically escape inputs:
// Safe approach using parameterized queries
const userId = validateTokenClaims(decoded.payload).userId;
const user = await db.collection('users').findOne({ _id: new ObjectId(userId) });Third, implement strict database permissions. The database user handling Bearer Token authentication should have minimal privileges:
// Database user permissions (pseudo-code)
db.createUser({
user: 'api_auth',
pwd: 'strong_password',
roles: [{ role: 'read', db: 'application' }]
});For applications requiring dynamic collection access, use a whitelist approach:
const allowedCollections = new Set(['users', 'orders', 'products']);
const collectionName = validateTokenClaims(decoded.payload).collection;
if (!allowedCollections.has(collectionName)) {
throw new Error('Unauthorized collection access');
}
const results = await db.collection(collectionName).find({});Finally, implement comprehensive logging and monitoring to detect injection attempts. Log all queries with their originating token claims and set up alerts for suspicious patterns like $where operator usage or excessive query results.