Missing Authentication in Express with Bearer Tokens
Missing Authentication in Express with Bearer Tokens
Missing authentication in an Express API that relies on Bearer tokens occurs when endpoints intended to be protected do not validate the presence or correctness of an Authorization header. This specific combination is common because Bearer tokens are simple to implement, yet easy to misconfigure. An endpoint that should require a token may omit a check, or may only verify the token exists without validating its signature, scope, or expiration. When this happens, any unauthenticated attacker can send a request with or without a token and receive the same response as an authenticated user.
In practice, this vulnerability often maps to the Broken Object Level Authorization (BOLA) / Insecure Direct Object References (IDOR) category, because the absence of authentication removes the boundary that prevents unauthorized subject access to specific resources. For example, an endpoint like GET /api/users/:userId that does not enforce token validation may allow an attacker to iterate over numeric IDs and view other users’ data. MiddleBrick scans this attack surface in black-box mode, testing unauthenticated paths and reporting findings such as missing authentication requirements alongside over-privileged behaviors.
Another subtle issue arises when authentication is present but improperly enforced across routes. Consider an Express app that applies token verification to some routes and not others, or applies it conditionally based on environment variables. A route may include a middleware check only for certain HTTP methods, or may call a verification function but not act on its result. These inconsistencies create a subset of endpoints that are effectively unauthenticated from an attacker’s perspective. MiddleBrick’s parallel security checks detect authentication gaps by sending requests both with and without valid tokens and comparing responses, highlighting endpoints where authentication is missing or bypassed.
Bearer token implementations may also be vulnerable when tokens are accepted via multiple sources, such as both the Authorization header and a cookie, without clear precedence rules. If an endpoint reads from a cookie when the header is absent, an attacker who can inject a cookie (e.g., via XSS or a misconfigured CORS or CROS configuration) may effectively bypass intended authentication. This cross-source acceptance without strict validation further expands the unauthenticated attack surface. MiddleBrick’s checks include analysis of such configurations by observing how the API behaves when no Authorization header is provided and alternate credential mechanisms are present.
Real-world attack patterns include enumeration of user IDs, access to administrative endpoints, and retrieval of sensitive data such as email addresses or internal identifiers. These map closely to OWASP API Top 10 categories, particularly Broken Object Level Authorization and Missing or Broken Authentication. Because Bearer tokens are widely used with JWTs, improper validation of token structure, issuer, audience, or expiration can compound the risk. MiddleBrick’s scans identify these gaps and provide prioritized findings with severity ratings and remediation guidance so teams can tighten authentication requirements across all routes.
Bearer Tokens-Specific Remediation in Express
Remediation focuses on ensuring every protected route validates Bearer tokens consistently and correctly. The recommended approach is to implement a centralized middleware function that checks for the presence of a Bearer token, validates its format, and, when applicable, verifies its signature and claims before allowing the request to proceed.
Below is a concrete example of a token verification middleware in Express that extracts a Bearer token from the Authorization header and performs basic validation. This pattern makes it explicit when authentication is required and avoids accidental bypasses.
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
// If using JWTs, verify signature and claims here.
// For opaque tokens, validate against a store or introspection endpoint.
// Placeholder for verification logic:
const isValid = verifyBearerToken(token); // implement this
if (!isValid) {
return res.status(403).json({ error: 'Invalid or insufficient privileges' });
}
req.user = { token };
next();
}
function verifyBearerToken(token) {
// Implement signature verification, expiration check, audience/issuer validation.
// For example, with jsonwebtoken:
// try { return jwt.verify(token, PUBLIC_KEY, { audience: 'my-api', issuer: 'https://auth.example.com' }); }
// catch { return false; }
return true; // simplified for example
}
app.get('/api/me', authenticateToken, (req, res) => {
res.json({ user: req.user });
});
app.get('/api/admin/settings', authenticateToken, (req, res) => {
res.json({ settings: { /* sensitive settings */ } });
});
For APIs documented with an OpenAPI specification, ensure that security schemes are declared and that paths requiring authentication reference the security requirement. This aligns static analysis with runtime behavior and supports tools that correlate spec definitions with scan findings.
paths:
/api/me:
get:
summary: Get current user
security:
- bearerAuth: []
responses:
'200':
description: OK
/api/admin/settings:
get:
summary: Get admin settings
security:
- bearerAuth: []
responses:
'200':
description: OK
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
When tokens are opaque, integrate an introspection check or validate against a trusted key set. Avoid accepting tokens from untrusted sources or skipping validation for localhost or test origins. Apply the middleware consistently across all routes that require protection, and avoid conditional or method-specific application that could leave gaps. MiddleBrick’s CLI and Web Dashboard can help verify that authentication requirements are present and effective across your endpoints.
Additional hardening includes using short-lived tokens, enforcing HTTPS in production, and avoiding logging of full tokens. The Pro plan supports continuous monitoring so that changes to routes or authentication logic can be detected and rescans triggered automatically. For development workflows, the CLI allows quick scans from the terminal with middlebrick scan <url>, while the GitHub Action can fail builds if risk scores drop below your chosen threshold.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |