Missing Tls in Adonisjs with Jwt Tokens
Missing Tls in Adonisjs with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Transport Layer Security (TLS) is the baseline mechanism for protecting data in transit. When an AdonisJS application issues or validates JSON Web Tokens (JWTs) over a connection that lacks TLS, tokens and all claims they carry can be observed and altered by network intermediaries. MiddleBrick’s scans detect unauthenticated endpoints serving tokens or authentication-related cookies without TLS, which exposes the JWT in cleartext across the network. This scenario commonly arises in development or misconfigured staging environments where HTTPS is not enforced or load balancers handle termination without strict transport checks. Even if JWTs are cryptographically signed, confidentiality is not provided; an attacker who can eavesdrop on the traffic can read sensitive claims (such as roles or scopes) and potentially reuse the token if it is not protected by additional mechanisms like the Secure and HttpOnly flags.
JWT-specific risks are compounded when tokens are passed in URLs or non-HttpOnly cookies, because they can be leaked via logs, Referer headers, or browser history. MiddleBrick’s checks for Data Exposure and Unsafe Consumption identify endpoints that transmit tokens without transport protections and surface them as high-severity findings. The scanner also flags missing HTTP Strict Transport Security (HSTS) headers, which prevent clients from accidentally downgrading to HTTP. Without TLS, mechanisms like rate limiting and input validation still operate, but the confidentiality and integrity boundaries they attempt to uphold are undermined because the token itself is exposed or modifiable in transit.
In an AdonisJS stack, typical patterns that lead to this vulnerability include omitting middleware that enforces HTTPS in production, terminating TLS at a proxy without configuring the application to recognize secure origins, and failing to set SameSite and Secure attributes on cookies. MiddleBrick’s OpenAPI/Swagger analysis correlates spec definitions with runtime behavior; if the spec lists securitySchemes of type oauth2 or http with bearerFormat JWT but the server serves tokens over plain HTTP, the cross-reference highlights a Transport security gap. Attack patterns such as passive sniffing on shared networks and SSL stripping remain relevant when TLS is absent, and the scanner surfaces such findings under Data Exposure and Encryption checks.
Jwt Tokens-Specific Remediation in Adonisjs — concrete code fixes
Remediation centers on enforcing TLS for all token issuance and validation paths and hardening how tokens are handled by the application. In AdonisJS, you can enforce HTTPS globally using the start/hooks.ts file to redirect HTTP requests before routing occurs. Below is a concise, working example that ensures every request uses TLS in production, protecting JWTs in transit.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { middleware } from '@ioc:Adioc/helpers'
export default class ForceHttpsMiddleware {
public async handle({ request, response, urlGenerator }: HttpContextContract, next: () => Promise) {
if (request.url().startsWith('/api/auth')) {
if (process.env.NODE_ENV === 'production' && !request.secure) {
return response.redirect(urlGenerator.make(request.url(), {}, { protocol: 'https' }))
}
}
await next()
}
}
For applications behind proxies or load balancers, configure the trusted proxy middleware and ensure the app respects the X-Forwarded-Proto header. The following snippet sets secure cookies for JWTs, which prevents leakage through browser storage and reduces exposure to certain client-side attacks. This configuration belongs in start/hooks.ts or a dedicated cookie configuration file.
import { Cookie } from '@ioc:Adonis/Core/Cookie'
Cookie.exchange('auth_token', {
secure: true,
sameSite: 'strict',
httpOnly: true,
path: '/',
encrypt: true,
})
When issuing tokens, ensure the response that carries the JWT uses HTTPS. A typical login route in AdonisJS might look like the following, demonstrating how to set a secure, HttpOnly cookie after successful authentication. This pattern aligns with JWT best practices by avoiding exposure in URLs and local storage.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { DateTime } from 'luxon' import Token from 'App/Models/Token' export default class AuthController { public async login({ request, response, auth }: HttpContextContract) { const { email, password } = request.only(['email', 'password']) const user = await User.findByOrFail('email', email) const isValid = await auth.attempt(email, password) if (!isValid) { return response.unauthorized({ message: 'Invalid credentials' }) } const token = await user.related('tokens').create({ type: 'api_access_token', expiresAt: DateTime.local().plus({ days: 7 }), }) return response .cookie('auth_token', token.token, { httpOnly: true, secure: true, sameSite: 'strict', path: '/', }) .send({ message: 'Authenticated' }) } }Validation and introspection endpoints that accept JWTs should also enforce TLS and validate token metadata rigorously. The following example shows how to protect an authenticated route using AdonisJS middleware, verifying the token and ensuring the request arrived over HTTPS before allowing access to protected resources.
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import { middleware } from '@ioc:Adonis/Core/Middleware' import jwt from '@ioc:Adonis/Addons/Jwt' export default class JwtAuthMiddleware { public async handle({ request, response }: HttpContextContract, next: () => Promise) { if (process.env.NODE_ENV === 'production' && !request.secure) { return response.unauthorized({ message: 'Insecure channel' }) } const payload = await jwt.verify(request.header('authorization')?.replace('Bearer ', '')) request.authUser = payload await next() } } Finally, integrate MiddleBrick’s scans to continuously verify that TLS is enforced for all token-related endpoints. The CLI tool allows you to validate configurations from the terminal, while the GitHub Action can fail builds if risk scores drop below your defined threshold, and the MCP Server enables scanning directly from your IDE as you develop. The Dashboard tracks your API security scores over time, helping you correlate fixes with improved findings across Authentication, Data Exposure, and Encryption checks.
Related CWEs: encryption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-319 | Cleartext Transmission of Sensitive Information | HIGH |
| CWE-295 | Improper Certificate Validation | HIGH |
| CWE-326 | Inadequate Encryption Strength | HIGH |
| CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | HIGH |
| CWE-328 | Use of Weak Hash | HIGH |
| CWE-330 | Use of Insufficiently Random Values | HIGH |
| CWE-338 | Use of Cryptographically Weak PRNG | MEDIUM |
| CWE-693 | Protection Mechanism Failure | MEDIUM |
| CWE-757 | Selection of Less-Secure Algorithm During Negotiation | HIGH |
| CWE-261 | Weak Encoding for Password | HIGH |