HIGH broken authenticationhapijavascript

Broken Authentication in Hapi (Javascript)

Broken Authentication in Hapi with Javascript — how this specific combination creates or exposes the vulnerability

Hapi is a rich framework for building web applications and APIs in JavaScript, and its authentication story depends heavily on how developers configure routes, strategies, and session handling. When authentication is implemented incorrectly in Hapi using JavaScript, it can lead to Broken Authentication, which enables attackers to bypass login controls, hijack sessions, or assume other users’ identities.

One common pattern is relying solely on cookie-based sessions without enforcing strict validation and secure attributes. For example, if a Hapi application uses the built-in cookie authentication scheme but does not set the isSecure, isHttpOnly, and sameSite flags appropriately, an attacker may be able to steal or manipulate session identifiers via cross-site scripting or insecure transmission. The following JavaScript configuration demonstrates an insecure setup:

const Hapi = require('@hapi/hapi');
const authCookie = {
  cookie: {
    name: 'session',
    password: 'weak-secret',
    isSecure: false,
    isHttpOnly: false,
    ttl: null,
    encoding: 'none',
    clearInvalid: false
  }
};

const server = Hapi.server({ port: 4000 });
server.auth.strategy('cookieAuth', 'cookie', authCookie);
server.auth.default('cookieAuth');

server.route({
  method: 'GET',
  path: '/profile',
  handler: (request, h) => {
    return request.auth.credentials;
  }
});

server.start();

In this example, isSecure: false allows the cookie to be sent over HTTP, making it trivial to capture via network sniffing. isHttpOnly: false exposes the cookie to client-side scripts, increasing the risk of cross-site scripting (XSS) theft. Missing sameSite settings can also enable cross-site request forgery (CSRF) to be chained with authentication bypass techniques.

Another vulnerability pattern arises when developers use weak or predictable identifiers for users in URLs and fail to enforce proper ownership checks. While this is categorized under BOLA/IDOR, it intersects with authentication when Hapi routes expose user-specific data without validating that the authenticated user owns the requested resource. For instance:

server.route({
  method: 'GET',
  path: '/users/{id}',
  handler: (request, h) => {
    const userId = request.auth.credentials.id;
    const requestedId = request.params.id;
    // Missing ownership validation
    return db.users.find(requestedId);
  },
  options: {
    auth: 'cookieAuth'
  }
});

An authenticated user could simply change /users/123 to /users/124 and access another account if the server does not confirm that userId === requestedId. This is a classic Broken Authentication flow rooted in missing authorization checks tied to the authenticated identity.

Hapi’s support for multiple authentication schemes means developers might inadvertently allow unauthenticated access to sensitive routes or misconfigure fallback behaviors. If a route defines an auth strategy but also relies on a default that is permissive, an attacker may exploit route-level misconfigurations to access protected endpoints without valid credentials.

Finally, weak password handling and improper session invalidation in JavaScript code further exacerbate the risk. Hardcoded secrets, lack of salting, and failing to clear server-side session state on logout all contribute to authentication weaknesses that Hapi applications written in JavaScript are susceptible to when best practices are ignored.

Javascript-Specific Remediation in Hapi — concrete code fixes

To mitigate Broken Authentication in Hapi using JavaScript, enforce strict cookie settings, validate ownership for every resource access, and adopt secure session management patterns. Below are concrete, secure configurations and code examples.

First, configure cookie authentication with security flags enabled:

const authCookie = {
  cookie: {
    name: 'session',
    password: process.env.AUTH_SECRET,
    isSecure: true,
    isHttpOnly: true,
    sameSite: 'strict',
    ttl: 24 * 60 * 60 * 1000,
    encoding: 'base64json',
    clearInvalid: true
  }
};

const server = Hapi.server({ port: 4000 });
server.auth.strategy('cookieAuth', 'cookie', authCookie);
server.auth.default('cookieAuth');

Setting isSecure: true ensures cookies are only sent over HTTPS. isHttpOnly: true protects the cookie from JavaScript access, mitigating XSS impact. sameSite: 'strict' reduces CSRF risk. Use a strong, environment-derived secret and avoid encoding: 'none'.

Second, always validate ownership of resources. Here is a secure route handler that confirms the authenticated user matches the requested user ID:

server.route({
  method: 'GET',
  path: '/users/{id}',
  handler: (request, h) => {
    const userId = request.auth.credentials.id;
    const requestedId = request.params.id;
    if (userId !== requestedId) {
      throw Boom.unauthorized('You cannot access this resource');
    }
    return db.users.find(requestedId);
  },
  options: {
    auth: 'cookieAuth'
  }
});

This pattern ensures that even if an attacker manipulates the URL, the server enforces ownership based on the authenticated identity, addressing BOLA/IDOR concerns tied to authentication.

Third, implement proper session invalidation on logout:

server.route({
  method: 'POST',
  path: '/logout',
  handler: (request, h) => {
    request.cookieAuth.clear();
    return { message: 'Logged out' };
  },
  options: {
    auth: 'cookieAuth'
  }
});

request.cookieAuth.clear() removes the server-side session state and instructs the client to expire the cookie. Combine this with short cookie lifetimes and refresh token strategies where appropriate.

For applications using JWTs, avoid storing sensitive data in the payload and always verify signatures and expiration. Hapi’s @hapi/jwt plugin can be used securely:

const Jwt = require('@hapi/jwt');
await server.register(Jwt);

server.auth.strategy('jwt', 'jwt', {
  keys: process.env.JWT_SECRET,
  validate: (decoded, request, h) => {
    return { isValid: true, credentials: decoded };
  }
});

These JavaScript-specific fixes align with OWASP API Security Top 10 authentication flaws and help ensure that Hapi applications handle identity and session management safely.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

How does middleBrick detect authentication misconfigurations in Hapi APIs?
middleBrick runs unauthenticated black-box checks aligned with the Authentication and BOLA/IDOR categories, testing cookie handling, token validation, and resource ownership patterns without requiring credentials.
Can I integrate middleBrick into my CI/CD to catch Broken Authentication early?
Yes; with the Pro plan, you can use the GitHub Action to fail builds when security scores drop below your threshold and scan staging APIs before deploy.