️ Middlewares
Middleware functions are used to intercept requests before they reach the main logic of the application. In Lila, core middlewares are defined in lila/core/middleware.py and re-exported from lila.core.middleware. Middlewares can be used for tasks such as authentication, logging, security, and error handling.
Lila exposes two families:
- Route decorators:
login_required,session_active,admin_required,rate_limit,csrf_protect(aliascsrf),validate_token,create_decorator. - Pure ASGI classes:
LoggingMiddleware,SecurityHeadersMiddleware,RateLimitMiddleware,StaticCacheMiddleware, plus Starlette'sMiddlewarefactory used byApp(middleware=[...]).
Default Route Middlewares
Lila includes several built-in middlewares that can be used as decorators on your routes:
-
@login_required: requires an active session. Pages get a303redirect to/login;/api/requests get401. It also setsrequest.state.user. -
@session_active: redirects already-authenticated users away from guest pages (default:/dashboard). -
@admin_required: checks theadmin_sessioncookie and setsrequest.state.admin(default redirect:/admin/login). -
@validate_token: validates a JWT from theAuthorization: Bearer <token>header and exposesrequest.state.jwt/request.state.jwt_user_id. -
@rate_limit(60, 60): per-route limiter backed byCache.incr_async(memory or Redis).
from lila.core.middleware import (
login_required, session_active, admin_required, validate_token, rate_limit,
)
from lila.core.request import Request
from lila.core.responses import JSONResponse
from lila.core.templates import render
# Require authentication for this route
@router.get('/dashboard')
@login_required
async def dashboard(request: Request):
return render(request, 'dashboard')
# Redirect authenticated users away from the login page
@router.get('/login')
@session_active
async def login_page(request: Request):
return render(request, 'login')
# Validate JWT for API routes
@router.get('/api/data')
@validate_token
async def api_data(request: Request):
return {"data": "secure", "user_id": request.state.jwt_user_id}
# Per-route rate limit: 30 requests per 60 seconds per client IP
@router.post('/api/contact')
@rate_limit(30, 60)
async def contact(request: Request):
return {"success": True}
# Admin-only page (uses the admin_session cookie)
@router.get('/admin/reports')
@admin_required
async def reports(request: Request):
return render(request, 'admin/reports')
️ Creating Custom Middlewares
You can easily create your own route middlewares using the create_decorator
helper. This tool automatically handles the boilerplate of Python decorators.
from lila.core.middleware import create_decorator
from lila.core.request import Request
from lila.core.responses import JSONResponse
@create_decorator
async def check_admin(request: Request, role="admin"):
# Returning a Response stops the chain and sends it to the client.
# Returning True or None lets the route handler run.
user = getattr(request.state, "user", None) or {}
if user.get("role") != role:
return JSONResponse({"error": "Unauthorized"}, status_code=403)
return True
# Usage in routes:
# @check_admin -> default role="admin"
# @check_admin(role="superadmin") -> custom role
️ Router-Level Middlewares
Instead of decorating every route manually, you can assign one or more middlewares to a Router during initialization. Every route registered on that router will inherit them and run them in left-to-right order.
from lila.core.routing import Router
from lila.core.middleware import login_required, rate_limit
# Both middlewares run for every route in this router, left to right.
auth_router = Router(prefix="/v1/api", middlewares=[login_required, rate_limit(120, 60)])
@auth_router.get("/user")
async def user_details(request: Request):
# login_required already populated request.state.user
return {"user": request.state.user}
CSRF Protection Middleware
Lila includes a built-in @csrf decorator that protects routes against Cross-Site Request Forgery attacks. It verifies the CSRF token on all unsafe HTTP methods (POST, PUT, PATCH, DELETE). Safe methods (GET, HEAD, OPTIONS) are always allowed through.
The token is read from the X-CSRF-Token header first, then from the parsed body (_csrf, csrf or csrf_token; JSON or form), and compared against the signed _csrf cookie set by render(). Tokens in the query string are intentionally not accepted.
from lila.core.templates import render
from lila.core.middleware import csrf
from lila.core.responses import JSONResponse
from lila.core.request import Request
# GET: render the form with CSRF token injected automatically
@router.get('/contact')
async def contact_page(request: Request):
return render(request, 'contact', csrf=True)
# POST: verify token before processing the form
@router.post('/contact')
@csrf
async def contact_submit(request: Request):
return JSONResponse({"success": True})
In your Jinja2 template, use the csrf_input global helper to render the hidden field:
<form method="POST" action="/contact">
{{ csrf_input | safe }}
<input type="text" name="name" />
<button type="submit">Send</button>
</form>
The Http() helper in public/js/lila-client.js reads the <meta name="csrf-token"> tag (present on every rendered page) and sends the X-CSRF-Token header on every fetch request. No additional client-side code is required.
Global Security Middlewares
Lila includes a set of global HTTP middlewares for application-wide protection. Pass them to
App(middleware=[...]):
LoggingMiddleware: Pure ASGI request logger (skips static files, redacts sensitive query keys).SecurityHeadersMiddleware: addsX-Content-Type-Options,X-Frame-Options,Referrer-Policy,Permissions-Policy,Cross-Origin-Opener-Policyand HSTS on HTTPS; blocks real traversal probes (.env,.git,../).RateLimitMiddleware: pure ASGI limiter backed byCache.incr_async(memory by default, Redis when configured) — not Redis-only.StaticCacheMiddleware: adds long-livedCache-Controlheaders to/public,/js,/img,/uploadsassets (immutable when the URL has?v=).csrf_protect/csrf: a route decorator that verifies CSRF for HTML form posts. The globalApp(csrf=True)guard covers JSON/header clients; form bodies are handled by the route-level check.
from starlette.middleware import Middleware
from lila.core.app import App
from lila.core.middleware import LoggingMiddleware, SecurityHeadersMiddleware
middlewares = [
Middleware(LoggingMiddleware),
Middleware(SecurityHeadersMiddleware),
]
app = App(routes=[router], middleware=middlewares, gzip=True)
# Shorthands are equivalent:
# app = App(routes=[router], logging=True, security=True, rate_limit=300)