Cross Site Request Forgery in Adonisjs with Basic Auth
Cross Site Request Forgery in Adonisjs with Basic Auth — how this specific combination creates or exposes the vulnerability
Cross Site Request Forgery (CSRF) in AdonisJS when using Basic Authentication creates a risk where an authenticated session can be abused across origins. Basic Auth sends credentials in each request, typically via the Authorization header, and when combined with cookie-based session handling or browser behavior that automatically includes those headers, this can enable CSRF if requests are not explicitly protected.
AdonisJS does not enable CSRF protection by default for API routes, which is appropriate for many stateless APIs. However, when Basic Auth is used in a context where the client relies on cookies—for example, a frontend JavaScript application that authenticates once with Basic Auth and then relies on session cookies for subsequent requests—an attacker can craft a request from another origin that the browser automatically sends with stored credentials. This is particularly relevant when the API serves HTML or is consumed by a Single Page Application that uses cookie-based sessions rather than token-based authentication.
The vulnerability arises when:
- Basic Auth credentials are accepted and a session or cookie is established.
- The application does not implement anti-CSRF tokens or same-site cookie attributes.
- The client includes credentials automatically for requests to the domain, including those initiated by third-party sites.
For example, an authenticated user visits a malicious site that contains an image tag or script making a request to your AdonisJS API endpoint that changes state (e.g., transferring funds or updating a record). If the browser automatically includes the Basic Auth Authorization header or a session cookie, the request is processed as legitimate. Because Basic Auth does not inherently protect against cross-origin credential inclusion, the server cannot distinguish a legitimate request from a forged one without additional defenses.
middleBrick detects this risk in its Authentication and BOLA/IDOR checks by analyzing whether endpoints that accept credentials also validate origin and implement CSRF protections or safe request patterns. The scanner highlights missing anti-CSRF measures when cookie-based sessions are inferred, even if the API primarily relies on Basic Auth headers.
Basic Auth-Specific Remediation in Adonisjs — concrete code fixes
To mitigate CSRF when using Basic Auth in AdonisJS, adopt defense-in-depth measures tailored to your application type. For pure API endpoints consumed by non-browser clients, ensure requests do not rely on cookies and require explicit credentials in headers. For web interfaces, combine Basic Auth with anti-CSRF tokens and secure cookie attributes.
1. Use Stateless Authentication and Avoid Cookies
Ensure API routes that use Basic Auth remain stateless and do not create session cookies. Configure AdonisJS to parse credentials strictly from headers and avoid storing authentication state in cookies.
// start/hooks.ts
import { defineConfig } from '@adonisjs/core'
export default defineConfig({
http: {
cookie: {
sameSite: 'none',
secure: true,
},
session: {
enabled: false, // Disable session cookies for API routes
},
},
})
By disabling sessions for API routes, you reduce the attack surface where cookies could be automatically included in cross-origin requests.
2. Enforce Origin and Referer Checks
Add middleware to verify the Origin or Referer header for state-changing requests. This complements Basic Auth by ensuring requests originate from trusted domains.
// middleware/csrf_protection.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export default class CsrfProtectionMiddleware {
public async handle(ctx: HttpContextContract, next: () => Promise) {
const allowedOrigin = 'https://your-trusted-frontend.com'
const origin = ctx.request.headers().origin
const referer = ctx.request.headers().referer
if (origin && origin !== allowedOrigin && referer && !referer.startsWith(allowedOrigin)) {
ctx.response.status(403).send('Forbidden: Invalid origin')
return
}
await next()
}
}
Register this middleware for routes that accept state-changing methods (POST, PUT, DELETE) and use Basic Auth.
3. Implement Anti-CSRF Tokens for Web Frontends
If your AdonisJS application serves HTML or works with a frontend that uses cookie-based sessions, generate and validate CSRF tokens. Store the token in a server-side session and require it for state-changing requests.
// middleware/csrf_token.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { csrf } from '@ioc:Adonis/Addons/Csrf'
export default class CsrfTokenMiddleware {
public async handle(ctx: HttpContextContract, next: () => Promise<void>) {
if (ctx.request.method === 'POST' || ctx.request.method === 'PUT' || ctx.request.method === 'DELETE') {
const token = ctx.request.header('x-csrf-token')
if (!token || !csrf.verify(token)) {
ctx.response.status(403).send('Invalid CSRF token')
return
}
}
await next()
}
}
In your views, inject the token into forms or fetch requests so that each state-changing request includes it.
4. Configure CORS Strictly
Limit which origins can interact with your API. Use AdonisJS CORS settings to restrict cross-origin requests even when credentials are present.
// start/cors.ts
import { cors } from '@ioc:Adonis/Addons/Cors'
export default cors.define((config) => {
config.enabled = true
config.allowOriginFn = (origin) => {
return origin === 'https://your-trusted-frontend.com'
}
config.allowCredentials = true
config.allowMethods = ['GET', 'POST', 'PUT', 'DELETE']
config.allowHeaders = ['Authorization', 'Content-Type']
})
This setup ensures that even with Basic Auth headers, only specified origins can make requests, reducing CSRF risk.
middleBrick’s GitHub Action can be integrated into CI/CD pipelines to automatically enforce these configurations and flag missing protections during development, helping teams maintain secure authentication patterns as applications evolve.