Secure your Mojara application
These examples show how to protect endpoints, prevent SQL injection, and handle uploaded files.
1. Require authentication
def private_page(req: Request) -> Response:
var token = req.headers.get("Authorization", "")
if token != "Bearer example-development-token":
return Response.json('{"error":"Authentication required"}', status=401)
return Response.json('{"private":true}')
Register app.get("/api/private", private_page).
Test it:
curl -i http://127.0.0.1:8000/api/private
curl -i -H "Authorization: Bearer example-development-token" \
http://127.0.0.1:8000/api/private
The first request returns 401; the second succeeds. The token is intentionally fixed for learning only. Real users must have securely generated and revocable credentials.
2. Never insert user input into SQL
Unsafe:
var sql = "SELECT * FROM users WHERE email = '" + email + "'"
Use binding:
var found = lease.query1("SELECT id FROM users WHERE email = $1", email)
The database interprets email as data, not SQL syntax.
3. Escape text inserted into HTML
A text value from the URL might contain markup. Escape special HTML characters before building an HTML response, or use a template engine that escapes automatically.
4. Protect cookies and credentials
Use HTTPS, mark cookies HttpOnly and Secure, choose a suitable SameSite policy and expire sessions when a user logs out. Passwords should be hashed using a password hashing function, not stored in plain text.
5. Validate uploads
Allow only necessary file types, apply per-file and per-request limits, generate server-side filenames and keep private files outside the public static directory.
6. Avoid leaking internal errors
Return JSON such as {"error":"Invalid input"} to the client. Record detailed diagnostics in server logs without exposing credentials or stack traces to public users.