Sql Injection with Bearer Tokens
How Sql Injection Manifests in Bearer Tokens
SQL injection in the context of bearer tokens occurs when token values are concatenated into SQL statements without proper parameterization. Attackers supply crafted tokens containing SQL meta-characters to manipulate query logic, bypass authentication, or extract data. Because bearer tokens are often passed as strings in headers and then used directly in database queries, they become a high-value injection vector.
One common pattern is dynamic query building where the token is interpolated into SQL. For example, a Node.js endpoint might extract Authorization: Bearer <token> and build a query like SELECT * FROM users WHERE session_token = '${token}'. If the token contains ' OR '1'='1, the query becomes a tautology that can return any row. Another pattern is using the token in an identifier context, such as a table or column name, where quoting cannot neutralize injection. Tokens stored in URL fragments or POST bodies are also used to construct dynamic SQL, for example via string formatting in Python:
query = f"SELECT role FROM tokens WHERE value = '{token}' AND user_id = {user_id}"
If token includes ' UNION SELECT secret FROM admin_users--, the attacker can read privileged data. Stored procedures called with token-driven parameters can also be vulnerable when dynamic SQL is built inside the procedure. In authentication flows, a token may be joined with user metadata, and if either source is untrusted, injection is possible. Because bearer tokens are often long, base64-like strings, they can evade naive allowlists, making injection harder to detect but trivial to exploit when concatenation is used.
In API gateways and service meshes, injection can appear in logging or telemetry queries that embed tokens in SQL-like filter strings. For instance, a gateway plugin might construct WHERE token = '{token}' inside a SQL-backed policy store. Attackers can probe with tokens like '-- to comment out remaining clauses and change the intended logic. These patterns are not theoretical; they map to real classes of vulnerabilities such as CWE-89 and are frequently found in custom authentication services that misuse bearer tokens as direct SQL inputs.
Bearer Tokens-Specific Detection
Detecting SQL injection in bearer token handling requires analyzing how tokens enter SQL execution paths. Static analysis can flag string interpolation in SQL-building code, but runtime testing is essential because many issues arise from indirect flows, such as token forwarding to internal services or logging layers. With middleBrick, you submit the API endpoint URL and the scanner runs black-box tests that include token-specific probes. It checks whether token values are properly parameterized and whether injection techniques—such as tautologies, union-based extraction, and error-based payloads—succeed when supplied as bearer tokens in the Authorization header.
The scanner executes requests like Authorization: Bearer ' OR 1=1-- and inspects responses for anomalies such as unexpected data disclosure or status-code deviations. Because OpenAPI specs often describe where the Authorization header is expected, middleBrick correlates spec definitions with runtime behavior to identify mismatches. If a spec indicates the token is used for authentication only, but the runtime behavior allows it to influence SQL filtering, this is flagged as a high-severity finding. The tool also tests token values in different positions—query parameters, headers, and body fields—that ultimately reach SQL execution, ensuring coverage of indirect injection paths.
Findings include details such as which endpoints are vulnerable, the payload that triggered the behavior, and the inferred SQL context. The report provides prioritized remediation guidance, mapping issues to frameworks like OWASP API Top 10 and PCI-DSS. By integrating middleBrick into CI/CD via the GitHub Action, you can automatically fail builds when SQL injection risks are detected in bearer token handling, preventing vulnerable code from reaching production.
For continuous assurance, the Pro plan enables scheduled scans so that changes to token handling or SQL logic are caught early. The dashboard tracks scores over time, helping teams understand how token-related security evolves as endpoints change. This combination of specification analysis and active testing is critical for identifying bearer token SQL injection, which is often missed by generic scanners that do not specialize in API security.
Bearer Tokens-Specific Remediation
Remediation centers on ensuring bearer tokens never directly interpolate into SQL. Use parameterized queries or prepared statements, and treat tokens as opaque values that flow to authentication layers without being re-interpreted as SQL. Below are concrete examples in common languages and frameworks.
Node.js with PostgreSQL and bearer token validation
import { Pool } from 'pg';
import jwt from 'jsonwebtoken';
const pool = new Pool();
export async function verifySession(req, res) {
const auth = req.headers['authorization'];
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized' });
}
const token = auth.split(' ')[1];
try {
// Validate token structure without SQL usage
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const userId = decoded.sub;
// Use parameterized query: token never becomes SQL code
const result = await pool.query(
'SELECT role FROM sessions WHERE user_id = $1 AND token = $2',
[userId, token]
);
res.json(result.rows);
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
}
This approach ensures the token is passed as a parameter, not concatenated. The SQL engine treats it strictly as a value, neutralizing injection.
Python with SQLAlchemy and bearer token scope checks
from sqlalchemy import text
from fastapi import Depends, HTTPException, Security
from fastapi.security import HTTPBearer
security = HTTPBearer()
def get_db_session(token: str = Security(security)):
# Validate token via your auth provider; do not embed in SQL string
if not is_valid_token(token.credentials):
raise HTTPException(status_code=401, detail='Invalid token')
# Use bound parameters in SQLAlchemy text() for dynamic filters
statement = text('SELECT * FROM resources WHERE owner_id = :uid AND scope = :scope')
result = db_session.execute(statement, {'uid': current_user_id, 'scope': token.credentials[:32]})
return result.fetchall()
Here, token values are bound as named parameters, avoiding string interpolation. Even when using token-derived values (e.g., a hash prefix), always pass them as parameters rather than building SQL text.
Java with JWT and PreparedStatement
@GET
@Path("/data")
public Response getData(@HeaderParam("Authorization") String authToken) {
if (authToken == null || !authToken.startsWith("Bearer ")) {
throw new NotAuthorizedException("Bearer token missing");
}
String token = authToken.substring("Bearer ".length());
String sql = "SELECT * FROM sessions WHERE token = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, token);
ResultSet rs = ps.executeQuery();
// process results
} catch (SQLException e) {
throw new InternalServerErrorException();
}
}
Using PreparedStatement with placeholders ensures the token cannot alter query structure. These patterns align with defenses for CWE-89 and are applicable regardless of the framework, as long as tokens are never treated as executable SQL.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |