On this page

FastAPI Task Manager: Ownership, JWT Auth, and Rate Limiting

Published on August 14, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A Task Manager API with no access control at all treats every task as visible and editable by anyone who calls the endpoint — there's no concept of "my tasks" versus "someone else's tasks," and nothing to stop one account from reading or modifying another's data. Wiring together JWT authentication, per-user ownership, an admin role, and rate limiting on the authentication routes is what turns a working CRUD API into one that's actually safe to expose to real users. Every file below is shown in full, with the reasoning behind each specific decision — not just what the code does, but why it's written the way it is.

info

This exercise is the continuation of hands-on exercises compelted in the previous modules. Be sure to check the previous parts to follow along:


What This Adds to the API​

Four capabilities get built into the existing Task Manager here. User ownership links every task to the account that created it through a user_id foreign key, with every query scoped to the authenticated user so data never leaks across accounts. Per-user access control runs through a get_current_user dependency that decodes the JWT on every protected request and returns the authenticated User object. Admin-only endpoints are gated by a separate require_admin dependency. And POST /auth/signup and POST /auth/login are rate-limited per IP to blunt brute-force and credential-stuffing attempts against the two most commonly targeted routes in any authentication system.


The User Model with a Role Field​

models/user.py:


from sqlmodel import SQLModel, Field, Relationship

from typing import Optional, List



class User(SQLModel, table=True):

    id: Optional[int] = Field(default=None, primary_key=True)

    username: str = Field(index=True, unique=True)

    email: str

    hashed_password: str

    is_active: bool = True

    role: str = "user"

    tasks: List["Task"] = Relationship(back_populates="user")

role defaults to "user", with "admin" as the only other value this project actually checks for. A plain string field is sufficient for what's being built here — a stricter str-based Enum can enforce that only those two specific values are ever accepted at the validation layer, closing off a typo like "admn" silently creating a role that matches nothing. tasks is the SQLModel relationship attribute enabling an ORM-level join back to Task, distinct from the actual foreign key column that lives on the Task side.


The Task Model with Ownership​

models/task.py:


from sqlmodel import SQLModel, Field, Relationship

from typing import Optional

from models.user import User



class Task(SQLModel, table=True):

    id: Optional[int] = Field(default=None, primary_key=True)

    title: str

    description: Optional[str] = None

    completed: bool = False

    user_id: Optional[int] = Field(default=None, foreign_key="user.id")

    user: Optional[User] = Relationship(back_populates="tasks")

user_id is the actual foreign key column stored in the database; user is the relationship attribute used for ORM-level joins, letting task.user.username be accessed directly without a separate query. Ownership enforcement itself happens in the service layer rather than here in the model — the model stays a pure data definition, and the actual "does this user own this task" logic lives in one place, covered further down.


A Single Shared Limiter Instance​

SlowAPI requires exactly one Limiter instance, registered on app.state.limiter. Defining it directly inside a router file and importing it into main.py from there couples main.py to that router's internal structure — the cleaner pattern is a dedicated module holding the single shared instance, imported wherever it's needed:

core/limiter.py:


from slowapi import Limiter

from slowapi.util import get_remote_address



limiter = Limiter(key_func=get_remote_address)

This one object gets imported into main.py to register it on app.state, and into routers/auth.py to apply the @limiter.limit() decorators — any additional router needing rate limiting imports from this same module, so there's never more than one Limiter instance anywhere in the application.


Authentication Dependencies: Current User and Role Guards​

core/dependencies.py:


from fastapi import Depends, HTTPException, status

from fastapi.security import OAuth2PasswordBearer

from core.jwt import decode_access_token

from sqlmodel import Session, select

from db import get_session

from models.user import User



oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")



def get_current_user(

    token: str = Depends(oauth2_scheme),

    session: Session = Depends(get_session),

) -> User:

    credentials_exception = HTTPException(

        status_code=status.HTTP_401_UNAUTHORIZED,

        detail="Invalid or expired token",

        headers={"WWW-Authenticate": "Bearer"},

    )



    payload = decode_access_token(token)

    if not payload or "sub" not in payload:

        raise credentials_exception



    user = session.exec(select(User).where(User.username == payload["sub"])).first()

    if not user:

        raise credentials_exception  # 401, not 404 — the token is no longer valid



    if not user.is_active:

        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account is disabled")



    return user



def require_admin(user: User = Depends(get_current_user)) -> User:

    if user.role != "admin":

        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")

    return user



def require_active_user(user: User = Depends(get_current_user)) -> User:

    # is_active is already checked inside get_current_user.

    # This dependency exists as a named alias that makes intent

    # explicit at the route level.

    return user

A valid token that no longer maps to any user — because the account was deleted after the token was issued — returns 401 Unauthorized, not 404 Not Found: the token itself has failed to authenticate anyone, which is exactly what 401 communicates, while 404 would misleadingly imply a resource that might exist somewhere else. The WWW-Authenticate: Bearer header on that response is required by RFC 6750 for Bearer token authentication failures specifically. Checking is_active centrally, inside get_current_user itself rather than in each individual route or dependency, guarantees every protected route in the application rejects a deactivated account automatically — no route author needs to remember to add that check anywhere. require_active_user depends on get_current_user rather than duplicating its token-decoding logic — FastAPI's dependency system caches a given dependency's resolution within a single request, so a route injecting both require_active_user and, elsewhere, get_current_user directly still only triggers one token decode and one database query per request, not two.


The Auth Router with Rate Limiting​

routers/auth.py:


from fastapi import APIRouter, Depends, HTTPException, Request

from sqlmodel import Session, select

from models.user import User

from db import get_session

from core.security import hash_password, verify_password

from core.jwt import create_access_token

from core.limiter import limiter

from fastapi.security import OAuth2PasswordRequestForm



router = APIRouter(prefix="/auth", tags=["Auth"])



@router.post("/signup", status_code=201)

@limiter.limit("3/minute")

def signup(

    request: Request,

    user: User,

    session: Session = Depends(get_session),

):

    existing_user = session.exec(select(User).where(User.username == user.username)).first()

    if existing_user:

        raise HTTPException(status_code=400, detail="Username already exists")



    user.hashed_password = hash_password(user.hashed_password)

    session.add(user)

    session.commit()

    session.refresh(user)

    return {"message": "User created", "user_id": user.id}



@router.post("/login")

@limiter.limit("5/minute")

def login(

    request: Request,

    form_data: OAuth2PasswordRequestForm = Depends(),

    session: Session = Depends(get_session),

):

    user = session.exec(select(User).where(User.username == form_data.username)).first()

    if not user or not verify_password(form_data.password, user.hashed_password):

        raise HTTPException(status_code=401, detail="Invalid credentials")



    token = create_access_token({"sub": user.username})

    return {"access_token": token, "token_type": "bearer"}

request: Request in both function signatures is mandatory, not optional — SlowAPI's key_func reads the client's identity directly off the request object, and if that parameter is absent, SlowAPI has nothing to extract an IP from and the limit silently doesn't apply at all, with no error raised anywhere to indicate the mistake. @limiter.limit() needs to sit below the route decorator, not above it, for the same reason decorator order matters generally in Python — reversing it breaks the limiter's ability to wrap the route correctly.


Registering Everything in main.py​


from contextlib import asynccontextmanager

from fastapi import FastAPI

from fastapi.middleware.cors import CORSMiddleware

from slowapi.errors import RateLimitExceeded

from slowapi import _rate_limit_exceeded_handler

from sqlmodel import SQLModel

from db import engine

from routers.auth import router as auth_router

from routers.tasks import router as tasks_router

from routers.admin import router as admin_router

from core.limiter import limiter



@asynccontextmanager

async def lifespan(app: FastAPI):

    SQLModel.metadata.create_all(engine)

    yield



app = FastAPI(lifespan=lifespan)



# Rate limiting — single limiter instance shared with all routers

app.state.limiter = limiter

app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)



# CORS

app.add_middleware(

    CORSMiddleware,

    allow_origins=["http://localhost:3000", "https://myfrontend.com"],

    allow_credentials=True,

    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],

    allow_headers=["Authorization", "Content-Type"],

)



app.include_router(auth_router)

app.include_router(tasks_router)

app.include_router(admin_router)

limiter here is the exact same object routers/auth.py uses for its decorators, imported from the shared module rather than redefined. app.state.limiter = limiter registers that instance with SlowAPI so it can correctly intercept and count requests across the whole application. allow_origins is set to an explicit list rather than a wildcard, which is what makes allow_credentials=True behave predictably — allow_methods and allow_headers are set explicitly here too, not because a wildcard on either of those specifically breaks anything with credentials enabled (Starlette's wildcard restriction applies to allow_origins only), but because listing exactly what's actually needed documents the API's real surface and keeps it from accepting headers or methods it was never designed to receive.


Enforcing Ownership in the Task Service​

services/task_service.py:


from sqlmodel import Session, select

from models.task import Task

from models.user import User

from fastapi import HTTPException



def create_task(task: Task, session: Session, user: User) -> Task:

    task.user_id = user.id

    session.add(task)

    session.commit()

    session.refresh(task)

    return task



def get_task_by_id(task_id: int, session: Session, user: User) -> Task:

    task = session.get(Task, task_id)

    if not task or task.user_id != user.id:

        raise HTTPException(status_code=404, detail="Task not found")

    return task



def update_task(task_id: int, updated: Task, session: Session, user: User) -> Task:

    task = get_task_by_id(task_id, session, user)

    task.title = updated.title

    task.description = updated.description

    task.completed = updated.completed

    session.commit()

    session.refresh(task)

    return task



def delete_task(task_id: int, session: Session, user: User) -> None:

    task = get_task_by_id(task_id, session, user)

    session.delete(task)

    session.commit()



def list_tasks(session: Session, user: User, completed: bool | None = None) -> list[Task]:

    query = select(Task).where(Task.user_id == user.id)

    if completed is not None:

        query = query.where(Task.completed == completed)

    return session.exec(query).all()



def list_tasks_paginated(

    session: Session,

    user: User,

    completed: bool | None = None,

    limit: int = 10,

    offset: int = 0,

) -> list[Task]:

    query = select(Task).where(Task.user_id == user.id)

    if completed is not None:

        query = query.where(Task.completed == completed)

    query = query.offset(offset).limit(limit)

    return session.exec(query).all()

get_task_by_id returns the same 404 whether the task genuinely doesn't exist or exists but belongs to a different user — both cases produce an identical response. This is deliberate: returning a different status, 403 Forbidden, for a task that exists but belongs to someone else would confirm to whoever's calling that a given ID is valid, which lets an attacker enumerate real task IDs across every account just by watching which status code comes back. Keeping the response identical in both cases removes that information entirely.


The Task Router​

routers/tasks.py:


from fastapi import APIRouter, Depends

from sqlmodel import Session

from db import get_session

from models.task import Task

from models.user import User

from services import task_service

from core.dependencies import require_active_user



router = APIRouter(prefix="/tasks", tags=["Tasks"])



@router.get("/")

def get_all(

    completed: bool | None = None,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    return task_service.list_tasks(session, user, completed)



@router.get("/paginated")

def get_paginated(

    completed: bool | None = None,

    limit: int = 10,

    offset: int = 0,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    return task_service.list_tasks_paginated(session, user, completed, limit, offset)



@router.get("/{task_id}")

def get_one(

    task_id: int,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    return task_service.get_task_by_id(task_id, session, user)



@router.post("/", status_code=201)

def create(

    task: Task,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    return task_service.create_task(task, session, user)



@router.put("/{task_id}")

def update(

    task_id: int,

    updated: Task,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    return task_service.update_task(task_id, updated, session, user)



@router.delete("/{task_id}", status_code=204)

def delete(

    task_id: int,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    task_service.delete_task(task_id, session, user)

Every route injects require_active_user directly as the value it needs — the User object it returns is both the identity check and the active-account guard in a single resolution, with no separate dependencies=[...] declaration needed alongside it. This is a meaningful detail: declaring require_active_user in both a route-level dependencies=[] list and again as an injected function parameter would resolve get_current_user twice per request, triggering a second token decode and database query unnecessarily — injecting it once, directly, is what keeps this to a single resolution while still giving the route the authenticated user object it needs to enforce ownership.


The Admin Router​

routers/admin.py:


from fastapi import APIRouter, Depends

from sqlmodel import Session, select

from db import get_session

from models.user import User

from core.dependencies import require_admin



router = APIRouter(prefix="/admin", tags=["Admin"])



@router.get("/users", dependencies=[Depends(require_admin)])

def list_users(session: Session = Depends(get_session)):

    return session.exec(select(User)).all()

list_users returns raw User ORM objects, which includes the hashed_password field in the response — even though the hash itself can't be reversed, exposing it at all in an API response is unnecessary and worth avoiding. A dedicated response schema excluding hashed_password closes this gap cleanly; it's a known, deliberate limitation of this specific route as shown here, not an oversight to build around.


Project File Structure​


project/

├── main.py

├── db.py

├── core/

│   ├── dependencies.py   ← get_current_user, require_admin, require_active_user

│   ├── jwt.py             ← create_access_token, decode_access_token

│   ├── limiter.py         ← shared Limiter instance

│   └── security.py        ← hash_password, verify_password

├── models/

│   ├── user.py

│   └── task.py

├── routers/

│   ├── auth.py             ← signup, login (rate-limited)

│   ├── tasks.py             ← CRUD, per-user ownership

│   └── admin.py             ← admin-only endpoints

└── services/

    └── task_service.py      ← business logic with ownership enforcement

Testing the Full Access-Control Layer in Swagger UI​

With the server running, /docs exercises every layer built here directly. Sending POST /auth/signup four times within a minute from the same IP returns 429 Too Many Requests on the fourth attempt. Sending POST /auth/login six times within a minute returns 429 on the sixth. Logging in as a user-role account, copying the token, and authorizing with it, then calling GET /tasks/ returns only that account's own tasks. Calling GET /admin/users with that same user-role token returns 403 Forbidden. Logging in as an admin account and repeating the same call returns 200 OK with the full user list.


Feature Summary​

FeatureWhere it livesHow it worksUser accountsmodels/user.py``User model with role and is_active fieldsTask ownershipmodels/task.py``user_id foreign key links every task to its creatorPer-user access controlcore/dependencies.py``get_current_user decodes the JWT and returns the authenticated userActive-user enforcementcore/dependencies.py``is_active check inside get_current_user, applied to every protected routeAdmin-only accesscore/dependencies.py``require_admin checks user.role == "admin"Auth rate limitingcore/limiter.py + routers/auth.pySingle Limiter instance; 3/minute on signup, 5/minute on loginCORSmain.py``CORSMiddleware with explicit origins, methods, and headers

Key Takeaways​

Every layer built here enforces exactly one concern, and that separation is what keeps the whole system easy to reason about: get_current_user handles authentication, require_admin and require_active_user handle authorization on top of it, and task_service.py handles ownership — never mixed together in a single route or a single check. Returning 404 uniformly for both a missing task and one owned by someone else closes an enumeration vector that a differentiated 403 response would otherwise open up. A single shared Limiter instance, defined once and imported everywhere it's needed, is what keeps app.state.limiter and every @limiter.limit() decorator referring to the exact same rate-tracking state rather than several disconnected ones.


Practice: Profile Endpoint, Role Promotion, and Ownership Verification​

A rate-limited profile endpoint using the existing get_current_user dependency:


@router.get("/me")

@limiter.limit("20/minute")

def get_profile(request: Request, current_user: User = Depends(get_current_user)):

    return {

        "username": current_user.username,

        "email": current_user.email,

        "role": current_user.role,

    }

request: Request is required here for the same reason it was required on signup and login — without it, @limiter.limit("20/minute") silently fails to apply.

An admin-only endpoint to change a user's role:


from pydantic import BaseModel



class RoleUpdate(BaseModel):

    role: str



@router.patch("/users/{user_id}/role", dependencies=[Depends(require_admin)])

def update_user_role(

    user_id: int,

    role_update: RoleUpdate,

    session: Session = Depends(get_session),

):

    user = session.get(User, user_id)

    if not user:

        raise HTTPException(status_code=404, detail="User not found")

    user.role = role_update.role

    session.add(user)

    session.commit()

    session.refresh(user)

    return {"message": "Role updated", "username": user.username, "role": user.role}

RoleUpdate as a dedicated schema, rather than accepting a raw string body directly, keeps the request shape self-documenting in /docs and leaves room to add validation — restricting role to a fixed set of accepted values — without changing the route's signature later.

Confirming ownership isolation end to end: creating two accounts, alice and bob, and logging in as each separately produces two distinct tokens. Creating a task as alice and then calling GET /tasks/ authenticated as bob returns an empty list — alice's task never appears, since list_tasks filters by Task.user_id == user.id and bob's user.id never matches it. Attempting GET /tasks/{alice_task_id} authenticated as bob returns 404 Not Found, not 403, exactly matching the ownership-enforcement pattern already built into get_task_by_id — confirming the same protection against ID enumeration holds even when tested directly against two real accounts rather than reasoned about in the abstract.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

HTTP Headers

Next

Advanced Features and Production Readiness