Fix Insecure API Management in Hapi
Insecure API management in Hapi usually manifests as exposed endpoints lacking rate limiting, proper authentication strategies, or granular authorization scopes. This 'open-door' policy invites automated scraping, credential stuffing, and Broken Object Level Authorization (BOLA) attacks. To secure a Hapi API, we must enforce a default authentication policy, integrate rate limiting, and use route-level scopes to validate resource ownership.
The Vulnerable Pattern
const Hapi = require('@hapi/hapi');const init = async () => { const server = Hapi.server({ port: 3000 });
server.route({ method: ‘GET’, path: ‘/api/data/{userId}’, handler: (request, h) => { // VULNERABILITY: No authentication, no rate limiting, no authorization check. // Any attacker can iterate userId to scrape the entire database. return getDataForUser(request.params.userId); } });
await server.start(); };
The Secure Implementation
The secure implementation fixes three critical flaws. First, it registers 'hapi-rate-limit' to prevent DoS and brute-force attempts. Second, it implements 'hapi-auth-jwt2' and sets it as the default strategy, ensuring no endpoint is public by accident. Third, it uses Hapi's dynamic scoping ('user-{params.userId}') to ensure that authenticated users can only access their own data, effectively mitigating BOLA vulnerabilities. By moving logic from the handler to the route configuration, we reduce the risk of developer error in access control checks.
const Hapi = require('@hapi/hapi'); const Jwt = require('hapi-auth-jwt2'); const RateLimit = require('hapi-rate-limit');const init = async () => { const server = Hapi.server({ port: 3000 });
// Register security plugins await server.register([ Jwt, { plugin: RateLimit, options: { userLimit: 50, pathLimit: 10 } } ]);
server.auth.strategy(‘jwt’, ‘jwt’, { key: process.env.JWT_SECRET, validate: async (decoded) => ({ isValid: !!decoded.id, credentials: decoded }) });
server.auth.default(‘jwt’);
server.route({ method: ‘GET’, path: ‘/api/data/{userId}’, options: { auth: { // Enforce scope: User must have admin role OR match the userId being requested access: { scope: [‘admin’, ‘user-{params.userId}’] } }, handler: (request, h) => getDataForUser(request.params.userId) } });
await server.start(); };
Your Hapi API
might be exposed to Insecure API Management
74% of Hapi apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.