Session Authentication

Stario uses standard HTTP cookies for session management.

1. Auth Middleware

Create a middleware to check for a session cookie and optionally attach the user to c.state.

def require_auth(next_handler):
    async def h(c, w):
        sid = c.req.cookies.get("session")
        user = await db.get_user_by_session(sid)

        if not user:
            return w.redirect("/login")

        c.state["user"] = user
        await next_handler(c, w)
    return h

2. Login Handler

When a user logs in, set a secure, HTTP-only cookie.

async def login(c: Context, w: Writer):
    signals = await c.signals()
    user = await authenticate(signals["user"], signals["pass"])

    if not user:
        return w.sync({"error": "Invalid credentials"})

    sid = await db.create_session(user.id)

    w.cookie(
        "session", 
        sid,
        httponly=True,    # Prevent JS access
        secure=True,      # HTTPS only (prod)
        samesite="lax",   # CSRF protection
        max_age=86400 * 7 # 7 days
    )
    w.navigate("/dashboard")

3. Logout Handler

async def logout(c: Context, w: Writer):
    w.delete_cookie("session")
    w.redirect("/login")

Key Security Tips

  • Always use httponly=True for session cookies to prevent token theft via XSS.
  • Use samesite="lax" or "strict" to block CSRF attacks.
  • Remove secure=True during local development if you aren't using HTTPS.