HIGH auth bypassadonisjs

Auth Bypass in Adonisjs

How Auth Bypass Manifests in Adonisjs

Authentication bypass in Adonisjs applications typically exploits middleware misconfiguration, token validation gaps, or session handling weaknesses. The framework's flexible middleware system, while powerful, creates attack surfaces when authentication guards are improperly applied or bypassed.

A common Adonisjs-specific pattern involves the auth middleware being omitted on routes that should be protected. Consider a dashboard route:

Route.get('/dashboard', async ({ auth, view }) => {
  return view.render('dashboard', {
    user: await auth.user
  })
})

Without auth middleware, this endpoint is accessible to anyone. The auth.user call will throw an error if no user is authenticated, but the route itself remains exposed.

Token-based bypass often occurs with JWT implementation flaws. Adonisjs's JWT guard expects tokens in the Authorization header, but if your application accepts tokens via query parameters or cookies without proper validation, attackers can manipulate the token source:

// Vulnerable: accepts tokens from multiple sources without validation
const token = request.input('token') || request.header('Authorization')
const user = await jwt.verify(token)

Session-based bypass targets Adonisjs's session guard configuration. If session secrets are weak or predictable, session fixation attacks become viable:

// Inconfig/secure.js
module.exports = {
  session: {
    secret: 'default-secret' // Predictable secret enables session hijacking
  }
}

Middleware ordering bugs create another attack vector. Adonisjs processes middleware in the order defined, so if authorization checks run before authentication, unauthenticated requests might reach protected resources:

// Vulnerable ordering
Route.get('/admin',
  'AdminController.checkPermissions', // Runs before auth check
  'AdminController.dashboard'
)

Model binding vulnerabilities occur when Adonisjs automatically resolves models from route parameters. If authorization checks don't validate that the authenticated user owns the requested resource, IDOR (Insecure Direct Object Reference) attacks become possible:

// Vulnerable: no ownership verification
Route.get('/posts/:id', async ({ params, auth }) => {
  const post = await Post.find(params.id)
  return post
})

Adonisjs-Specific Detection

Detecting authentication bypass in Adonisjs requires examining both code structure and runtime behavior. Start by auditing middleware usage patterns across your route definitions.

Static analysis should identify routes missing auth middleware:

// Scan for unprotected routes
const routes = require('./start/routes')
routes.forEach(route => {
  if (!route.middleware.includes('auth') && route.path !== '/') {
    console.warn(`Unprotected route: ${route.method} ${route.path}`)
  }
})

Token validation gaps appear when JWT configuration allows multiple token sources. Check your auth configuration:

// config/auth.js
module.exports = {
  guard: 'jwt',
  authenticator: 'jwt',
  jwt: {
    publicKey: Env.get('JWT_PUBLIC_KEY'),
    privateKey: Env.get('JWT_PRIVATE_KEY'),
    // Verify token source is restricted to Authorization header only
  }
}

Session security weaknesses manifest in predictable session secrets or missing secure cookie flags:

// Check session configuration
const sessionConfig = require('./config/session')
if (sessionConfig.secret === 'default-secret') {
  console.error('Predictable session secret detected')
}
if (!sessionConfig.cookie.secure) {
  console.error('Session cookies not marked as secure')
}

Middleware ordering issues require analyzing the execution chain. Create a diagnostic middleware to log execution order:

// start/middleware.js
const { HttpContext } = require('@adonisjs/core/http')
HttpContext.before(async (ctx) => {
  console.log(`[${new Date().toISOString()}] ${ctx.request.method()} ${ctx.request.url()}`)
  console.log('Middleware chain:', ctx.middleware.map(m => m.name))
})

middleBrick's API security scanner automatically detects Adonisjs-specific authentication bypass patterns through black-box testing. It identifies unprotected endpoints, tests JWT token manipulation, and verifies session handling security without requiring source code access or credentials.

The scanner's LLM security checks are particularly relevant for Adonisjs applications using AI features, testing for system prompt leakage and prompt injection vulnerabilities that could bypass authentication logic in AI-powered endpoints.

Adonisjs-Specific Remediation

Fixing authentication bypass in Adonisjs requires leveraging the framework's built-in security features and following established patterns. Start with comprehensive middleware protection.

Apply the auth middleware to all protected routes:

// start/routes.js
Route.group(() => {
  Route.get('/dashboard', 'DashboardController.show')
  Route.get('/profile', 'ProfileController.show')
}).middleware('auth') // Apply auth to entire group

For JWT implementations, restrict token sources and validate claims:

// app/Middleware/JwtValidator.js
const { HttpContext } = require('@adonisjs/core/http')

HttpContext.before(async (ctx) => {
  const authHeader = ctx.request.header('Authorization')
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    ctx.response.status(401).json({ error: 'Missing or invalid token' })
    return
  }
  
  const token = authHeader.substring(7)
  try {
    const payload = await use('jwt').verify(token)
    if (payload.exp < Date.now() / 1000) {
      throw new Error('Token expired')
    }
  } catch (error) {
    ctx.response.status(401).json({ error: 'Invalid token' })
    return
  }
})

Strengthen session security with strong secrets and secure cookie settings:

// config/session.js
module.exports = {
  secret: Env.get('SESSION_SECRET', crypto.randomBytes(32).toString('hex')),
  cookie: {
    secure: true, // Only send over HTTPS
    httpOnly: true, // Prevent JS access
    sameSite: 'strict' // Mitigate CSRF
  }
}

Implement proper middleware ordering with authorization guards:

// app/Middleware/Authorize.js
const { HttpContext } = require('@adonisjs/core/http')

HttpContext.before(async (ctx) => {
  const { auth } = ctx
  if (!(await auth.check())) {
    ctx.response.status(401).json({ error: 'Authentication required' })
    return
  }
  
  // Example: Check user role
  if (ctx.route.name.startsWith('admin') && !(await auth.user.hasRole('admin'))) {
    ctx.response.status(403).json({ error: 'Insufficient permissions' })
    return
  }
})

Prevent IDOR vulnerabilities with ownership validation:

// app/Controllers/Http/PostController.js
class PostController {
  async show({ params, auth, response }) {
    const post = await Post.find(params.id)
    if (!post) {
      return response.status(404).json({ error: 'Post not found' })
    }
    
    if (post.user_id !== auth.user.id) {
      return response.status(403).json({ error: 'Access denied' })
    }
    
    return post
  }
}

middleBrick's continuous monitoring in Pro plans automatically scans your Adonisjs APIs on a configurable schedule, alerting you when authentication bypass vulnerabilities appear. The GitHub Action integration lets you fail CI builds when security scores drop, ensuring authentication issues don't reach production.

For applications using AI features with Adonisjs, middleBrick's LLM security checks test for prompt injection vulnerabilities that could manipulate authentication logic in AI-powered endpoints, providing comprehensive protection beyond traditional API security.

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 can I test if my Adonisjs API has authentication bypass vulnerabilities?
Use middleBrick's 10-second self-service scan to test your API endpoints without credentials. The scanner automatically identifies unprotected routes, tests JWT token manipulation, and verifies session handling security. For development, you can audit your route definitions to ensure all protected endpoints have the 'auth' middleware applied, and verify that JWT tokens are only accepted from the Authorization header.
What's the difference between authentication bypass and authorization bypass in Adonisjs?
Authentication bypass allows attackers to access protected resources without any credentials at all, often through missing middleware or token validation flaws. Authorization bypass occurs when an authenticated user accesses resources they shouldn't have permission to view, typically through IDOR vulnerabilities where ownership checks are missing. Both are critical security issues, but authentication bypass is often more severe as it affects all users rather than just specific accounts.