Skip to content

Guide: Basic app

A credentials-only FastAuth app with one protected route. Run in five minutes. See examples/basic/.

This guide shows the corrected version. The shipped examples/basic/main.py (as of v0.5.7) uses require_role / require_permission without wiring auth.role_adapter — those routes return 500 RBAC is not configured. RBAC is covered in the separate RBAC guide.

Install

pip install "sreekarnv-fastauth[standard]"

main.py

from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI
from fastauth import FastAuth, FastAuthConfig
from fastauth.adapters.sqlalchemy import SQLAlchemyAdapter
from fastauth.api.deps import require_auth
from fastauth.email_transports.console import ConsoleTransport
from fastauth.providers.credentials import CredentialsProvider
from fastauth.types import UserData

adapter = SQLAlchemyAdapter(engine_url="sqlite+aiosqlite:///./auth.db")

auth = FastAuth(FastAuthConfig(
    secret="change-me-in-production-min-32-bytes!!",  # `fastauth generate-secret`
    providers=[CredentialsProvider()],
    adapter=adapter.user,
    token_adapter=adapter.token,
    email_transport=ConsoleTransport(),  # prints verification/reset emails to stdout
    base_url="http://localhost:8000",
))

@asynccontextmanager
async def lifespan(app: FastAPI):
    await adapter.create_tables()
    yield

app = FastAPI(title="FastAuth Basic", lifespan=lifespan)
auth.mount(app)

@app.get("/dashboard")
async def dashboard(user: UserData = Depends(require_auth)):
    return {"hello": user["email"], "user": user}

Run

uvicorn main:app --reload

Try it

curl -X POST http://localhost:8000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"a@b.com","password":"s3cur3-pw!","name":"A"}'

# ConsoleTransport prints the verification email (with a token) to stdout.
# Verify it (paste the raw token from the printed link):
curl "http://localhost:8000/auth/verify-email?token=..."

curl -X POST http://localhost:8000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"a@b.com","password":"s3cur3-pw!"}'

Where to go next