Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

docs: fix authentication middleware example to use pure ASGI middleware (#8473)

Myles Scolnick3b3df46d9b82
diff --git a/docs/guides/deploying/programmatically.md b/docs/guides/deploying/programmatically.md
index 930f5284ba..63b7cba8d8 100644
--- a/docs/guides/deploying/programmatically.md
+++ b/docs/guides/deploying/programmatically.md
@@ -86,29 +86,36 @@ mo.md(content)
### Authentication Middleware Example
-Here's an example of how to implement authentication middleware that populates `request.user`:
+Here's an example of how to implement authentication middleware that populates `request.user`.
+
+/// admonition | Use a pure ASGI middleware
+ type: warning
+
+Use a pure ASGI middleware (not Starlette's `BaseHTTPMiddleware`) so that
+`scope["user"]` and `scope["meta"]` are set for **both** HTTP and WebSocket
+connections. marimo uses WebSocket for real-time communication, and
+`BaseHTTPMiddleware` only runs for HTTP requests.
+///
```python
-from starlette.middleware.base import BaseHTTPMiddleware
-from starlette.requests import Request
-
-class AuthMiddleware(BaseHTTPMiddleware):
- async def dispatch(self, request: Request, call_next):
- # Add user data to the request scope
- # This will be accessible via mo.app_meta().request.user
- request.scope["user"] = {
- "is_authenticated": True,
- "username": "example_user",
- # Add any other user data
- }
-
- # Optional add metadata to the request
- request.scope["meta"] = {
- "some_key": "some_value",
- }
-
- response = await call_next(request)
- return response
+class AuthMiddleware:
+ def __init__(self, app):
+ self.app = app
+
+ async def __call__(self, scope, receive, send):
+ if scope["type"] in ("http", "websocket"):
+ # Add user data to the request scope
+ # This will be accessible via mo.app_meta().request.user
+ scope["user"] = {
+ "is_authenticated": True,
+ "username": "example_user",
+ # Add any other user data
+ }
+ # Optionally add metadata to the request
+ scope["meta"] = {
+ "some_key": "some_value",
+ }
+ await self.app(scope, receive, send)
# Add the middleware to your FastAPI app
app.add_middleware(AuthMiddleware)
diff --git a/examples/frameworks/fastapi-auth/README.md b/examples/frameworks/fastapi-auth/README.md
new file mode 100644
index 0000000000..a2a49448a2
--- /dev/null
+++ b/examples/frameworks/fastapi-auth/README.md
@@ -0,0 +1,24 @@
+# FastAPI + marimo: Authentication Middleware
+
+This example shows the recommended pattern for passing user info into marimo
+notebooks via `mo.app_meta().request.user` and `mo.app_meta().request.meta`.
+
+It includes:
+
+- Login / logout with session cookies
+- A **pure ASGI middleware** that sets `scope["user"]` and `scope["meta"]` for
+ both HTTP and WebSocket connections
+- A marimo notebook that reads user info via `mo.app_meta().request`
+
+### Why pure ASGI middleware?
+
+marimo uses WebSocket for real-time communication. Starlette's
+`BaseHTTPMiddleware` only runs for HTTP requests, so `scope["user"]` set there
+is not visible on WebSocket connections. A pure ASGI middleware handles both.
+
+## Running the app
+
+1. [Install `uv`](https://github.com/astral-sh/uv/?tab=readme-ov-file#installation)
+2. Run the app with `uv run --no-project main.py`
+3. Open http://localhost:8000/ and log in with `admin` / `password123`
+4. The notebook cell will display the authenticated user and meta data
diff --git a/examples/frameworks/fastapi-auth/main.py b/examples/frameworks/fastapi-auth/main.py
new file mode 100644
index 0000000000..4e96cf906c
--- /dev/null
+++ b/examples/frameworks/fastapi-auth/main.py
@@ -0,0 +1,182 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "fastapi",
+# "marimo",
+# "starlette",
+# "uvicorn",
+# "itsdangerous",
+# "python-multipart",
+# ]
+# ///
+"""Example: Authentication middleware that passes user info into marimo notebooks.
+
+This shows the recommended pattern for authentication with marimo when using
+FastAPI. It uses a pure ASGI middleware (not BaseHTTPMiddleware) so that
+scope["user"] and scope["meta"] are set for both HTTP *and* WebSocket
+connections.
+
+The user info is then available in notebooks via:
+
+ request = mo.app_meta().request
+ username = request.user["username"]
+
+Run with:
+ uv run --no-project main.py
+
+Then open http://localhost:8000/ and log in with admin / password123.
+"""
+
+import os
+import logging
+
+import marimo
+import uvicorn
+from fastapi import FastAPI, Request, Form
+from fastapi.responses import HTMLResponse, RedirectResponse
+from starlette.middleware.sessions import SessionMiddleware
+from starlette.responses import Response
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+notebook_dir = os.path.dirname(__file__)
+notebook_path = os.path.join(notebook_dir, "notebook.py")
+
+# Simulated user database (replace with a real database in production)
+users_db = {"admin": "password123"}
+
+app = FastAPI()
+
+
+# Pure ASGI middleware — runs for both HTTP and WebSocket requests.
+# This is the recommended pattern for passing user/meta into marimo.
+#
+# Important: Do NOT use Starlette's BaseHTTPMiddleware here.
+# BaseHTTPMiddleware only processes HTTP requests, not WebSocket
+# connections. marimo uses WebSocket for real-time communication,
+# so scope["user"] and scope["meta"] would be lost.
+#
+# This is a simplified version of authentication and you may want to use
+# starlette.middleware.authentication.AuthenticationMiddleware instead.
+class AuthMiddleware:
+ # Paths that don't require authentication
+ PUBLIC_PATHS = {"/login"}
+
+ def __init__(self, app):
+ self.app = app
+
+ async def __call__(self, scope, receive, send):
+ if scope["type"] not in ("http", "websocket"):
+ await self.app(scope, receive, send)
+ return
+
+ # SessionMiddleware has already run, so scope["session"] is available.
+ session = scope.get("session", {})
+ username = session.get("username")
+
+ if username:
+ # Set user/meta so marimo can read them via mo.app_meta().request
+ scope["user"] = {
+ "is_authenticated": True,
+ "username": username,
+ }
+ scope["meta"] = {"role": "admin"}
+ await self.app(scope, receive, send)
+ return
+
+ # Not logged in — block unauthenticated access.
+ path = scope.get("path", "")
+
+ # Allow public paths through without authentication.
+ if path in self.PUBLIC_PATHS:
+ await self.app(scope, receive, send)
+ return
+
+ # Reject unauthenticated WebSocket connections.
+ if scope["type"] == "websocket":
+ from starlette.websockets import WebSocket
+
+ ws = WebSocket(scope, receive, send)
+ await ws.close(code=4003)
+ return
+
+ # Redirect unauthenticated HTTP requests to /login.
+ response = Response(
+ status_code=302, headers={"location": "/login"}
+ )
+ await response(scope, receive, send)
+
+
+# Middleware ordering: In Starlette, the LAST added middleware is the
+# OUTERMOST (runs first). We need SessionMiddleware to run before
+# AuthMiddleware so that scope["session"] is populated. So we add
+# AuthMiddleware first (innermost) and SessionMiddleware last (outermost).
+app.add_middleware(AuthMiddleware)
+app.add_middleware(
+ SessionMiddleware,
+ secret_key=os.getenv("SECRET_KEY", "change-me-in-production"),
+)
+
+LOGIN_PAGE = """\
+<!DOCTYPE html>
+<html>
+<head><title>Login</title></head>
+<body style="display:flex;justify-content:center;align-items:center;height:100vh;font-family:sans-serif">
+ <form method="post" action="/login" style="width:300px">
+ <h2>Login</h2>
+ {error}
+ <div style="margin-bottom:8px">
+ <label>Username</label><br>
+ <input name="username" required style="width:100%;padding:6px">
+ </div>
+ <div style="margin-bottom:8px">
+ <label>Password</label><br>
+ <input name="password" type="password" required style="width:100%;padding:6px">
+ </div>
+ <button type="submit" style="width:100%;padding:8px">Log in</button>
+ </form>
+</body>
+</html>
+"""
+
+
+async def get_login():
+ return HTMLResponse(LOGIN_PAGE.format(error=""))
+
+
+async def post_login(
+ request: Request,
+ username: str = Form(...),
+ password: str = Form(...),
+):
+ if username in users_db and password == users_db[username]:
+ request.session["username"] = username
+ logger.info("User %s logged in", username)
+ return RedirectResponse(url="/", status_code=302)
+ logger.warning("Failed login attempt for %s", username)
+ return HTMLResponse(
+ LOGIN_PAGE.format(
+ error='<p style="color:red">Invalid credentials</p>'
+ )
+ )
+
+
+async def logout(request: Request):
+ request.session.clear()
+ return RedirectResponse(url="/login")
+
+
+# Mount marimo
+marimo_app = (
+ marimo.create_asgi_app(include_code=True)
+ .with_app(path="/", root=notebook_path)
+ .build()
+)
+app.mount("/", marimo_app)
+
+if __name__ == "__main__":
+ uvicorn.run(app, host="127.0.0.1", port=8000)
diff --git a/examples/frameworks/fastapi-auth/notebook.py b/examples/frameworks/fastapi-auth/notebook.py
new file mode 100644
index 0000000000..ae340d80b9
--- /dev/null
+++ b/examples/frameworks/fastapi-auth/notebook.py
@@ -0,0 +1,31 @@
+import marimo
+
+__generated_with = "0.20.0"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
+def _(mo):
+ req = mo.app_meta().request
+ user = req.user if req else None
+ meta = req.meta if req else None
+
+ mo.md(f"""
+ ## User info from `mo.app_meta().request`
+
+ - **user**: `{user}`
+ - **username**: `{user['username'] if isinstance(user, dict) else 'N/A'}`
+ - **meta**: `{meta}`
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.py
index bfc6a0f9bb..4406d9647c 100644
--- a/tests/_server/test_asgi.py
+++ b/tests/_server/test_asgi.py
@@ -372,6 +372,50 @@ class TestASGIAppBuilder(unittest.TestCase):
assert response.status_code == 200
assert custom_head in response.text
+ def test_asgi_auth_middleware_propagates_to_http_and_websocket(self):
+ """Test that a pure ASGI middleware sets scope['user'] and scope['meta']
+ for both HTTP and WebSocket connections (the recommended pattern)."""
+
+ # Track which scope types the middleware was invoked for
+ invoked_for: list[str] = []
+
+ class AuthMiddleware:
+ """Pure ASGI middleware that sets user/meta on both HTTP and WS."""
+
+ def __init__(self, app: ASGIApp):
+ self.app = app
+
+ async def __call__(
+ self, scope: Scope, receive: Receive, send: Send
+ ) -> None:
+ if scope["type"] in ("http", "websocket"):
+ invoked_for.append(scope["type"])
+ scope["user"] = {
+ "is_authenticated": True,
+ "username": "test_user",
+ }
+ scope["meta"] = {"tenant": "acme"}
+ await self.app(scope, receive, send)
+
+ builder = create_asgi_app(quiet=True, include_code=True)
+ marimo_app = builder.with_app(
+ path="/", root=self.app1, middleware=[AuthMiddleware]
+ ).build()
+
+ client = TestClient(marimo_app)
+
+ # HTTP request should succeed (middleware sets user)
+ response = client.get("/")
+ assert response.status_code == 200
+ assert "http" in invoked_for
+
+ # WebSocket should also have user/meta in scope.
+ with client.websocket_connect("/ws?session_id=test123") as ws:
+ data = ws.receive_text()
+ assert data # kernel-ready message
+
+ assert "websocket" in invoked_for
+
class TestDynamicDirectoryMiddleware(unittest.TestCase):
def setUp(self):