Auth Bypass in Adonisjs with Jwt Tokens
Auth Bypass in Adonisjs with Jwt Tokens — how this specific combination creates or exposes the vulnerability
An Auth Bypass in AdonisJS when using JWT tokens typically occurs when token validation, payload extraction, or guard configuration does not enforce strict authentication and authorization checks. AdonisJS relies on the underlying JWT package to verify tokens, but application-level decisions—such as which guards protect which routes and how tokens are parsed—determine whether a bypass is possible.
One common root cause is missing or inconsistent guard configuration on routes that should require authentication. If a route is not explicitly assigned an auth guard, AdonisJS may default to an unauthenticated state, allowing access without a valid JWT. Even when guards are used, incorrectly setting the JWT driver or provider can lead to a scenario where tokens are not validated as expected, enabling an authenticated context to be assumed without proof.
Another specific vector involves how the application extracts the token from the request. Relying on non-standard headers or query parameters, or failing to enforce the Authorization: Bearer scheme consistently, can expose an endpoint to token substitution or leakage attacks. If middleware does not properly reject malformed or missing tokens, an attacker can craft requests that bypass intended protections. Insecure token storage practices on the client side (e.g., storing tokens in localStorage without adequate mitigations) can also facilitate token theft and unauthorized use.
Payload issues further contribute to bypass risks. If the JWT payload contains overly permissive claims (such as broad role scopes or missing scope checks), the application may fail to enforce least-privilege access. Without validating token expiration and revocation mechanisms, replay attacks or the use of stale tokens may be possible. AdonisJS applications that do not validate issuer (iss), audience (aud), or other standard JWT claims may accept tokens intended for different services or environments.
Insecure implementation patterns compound these issues. Hardcoded secrets, weak key material, or improper key rotation can undermine the integrity of signed tokens. Misconfigured CORS policies may allow cross-origin requests with forged credentials. When logging or error handling inadvertently exposes tokens or internal paths, attackers gain clues for further exploitation. The combination of weak token handling, missing validation, and inconsistent route protections can lead to authentication bypass even when JWT is used throughout the stack.
Jwt Tokens-Specific Remediation in Adonisjs — concrete code fixes
To remediate Auth Bypass risks with JWT tokens in AdonisJS, focus on strict guard configuration, explicit middleware application, and secure token handling. Use AdonisJS auth providers and guards to enforce authentication on protected routes, and validate JWT claims beyond simple signature verification.
Define a specific JWT guard in config/auth.ts and reference it in your route middleware. For example, configure the JWT provider and ensure your API routes use the correct guard:
// config/auth.ts
import { AuthConfig } from '@ioc:Adonis/Addons/Auth'
const authConfig: AuthConfig = {
guard: 'api',
guards: {
api: {
driver: 'jwt',
provider: 'users',
tokenSigningKey: process.env.JWT_SECRET_KEY as string,
tokenEncryptionAlgorithm: 'HS256',
},
},
}
export default authConfig
Apply the auth middleware explicitly to routes that require authentication and specify the guard to avoid relying on defaults:
// start/routes.ts
import Route from '@ioc:Adonis/Core/Route'
Route.get('/profile', 'ProfileController.show')
.middleware('auth:api') // enforce the JWT guard
In your controller, validate token claims such as expiration, issuer, and audience to prevent acceptance of invalid tokens. Use the auth utilities to inspect the user and ensure proper scoping:
// app/Controllers/Http/ProfileController.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export default class ProfileController {
public async show({ auth, response }: HttpContextContract) {
const user = auth.getUserOrFail()
// Ensure token claims are validated server-side
if (!user.isActive) {
return response.unauthorized('Account is disabled')
}
return response.ok(user)
}
}
Enforce strict token extraction by requiring the Authorization header with the Bearer scheme and rejecting requests that do not conform. Avoid parsing tokens from query strings or custom headers unless strictly necessary and properly secured:
// middleware/ensureBearerToken.ts
import { Exception } from '@ioc:Adonis/Core/Exception'
export default async function ensureBearerToken({ request, auth }: HttpContextContract, next: () => Promise) {
const header = request.header('authorization')
if (!header || !header.startsWith('Bearer ')) {
throw new Exception('Unauthorized: Bearer token required', 401, 'E_UNAUTHORIZED')
}
await next()
}
Rotate signing keys regularly and avoid hardcoding secrets. Use environment variables and consider key versioning to support phased rotation without service disruption. Combine JWT validation with IP and device fingerprint checks where appropriate to further reduce bypass risk.
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 |