DOCUMENTATION / CORE FRAMEWORK

Authentication and protected routes

Learn sessions and cookies: set, read and delete cookies, login and logout, and cookie persistence.

A user must prove who they are before accessing private pages. Authorization determines what they may do after login.

1. Begin with a protected route

from mojara import App, Request, Response

def profile(req: Request) -> Response:
    var token = req.headers.get("Authorization", "")
    if token != "Bearer example-development-token":
        return Response.json('{"error":"Login required"}', status=401)
    return Response.json('{"user":"Amina","role":"member"}')

def main() raises:
    var app = App()
    app.get("/api/profile", profile)
    app.run(port=8000)

This first example uses a fixed development token only to demonstrate request authorization. Replace it with the framework's actual session or token validation for real users.

2. Test the protected route

curl -i http://127.0.0.1:8000/api/profile

The response should be 401 because the request has no token.

curl -i -H "Authorization: Bearer example-development-token" \
  http://127.0.0.1:8000/api/profile

This time the handler returns the JSON profile.

3. Add role checks

def admin_panel(req: Request) -> Response:
    var role = req.headers.get("X-Demo-Role", "")
    if role != "admin":
        return Response.json('{"error":"Forbidden"}', status=403)
    return Response.json('{"dashboard":"admin"}')

The header is only a learning demonstration. A real role must come from an authenticated account or server-side session, never directly from a client-controlled header.

4. Use real authentication in applications

For user accounts, implement password hashing, rate limits, session expiration, HTTPS-only cookies and explicit logout. Authentication and authorization are separate checks: a logged-in non-admin can still receive 403 Forbidden.

See Security for a complete checklist and HTTP API for error responses.