- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Authentication, Authorization and Security
- Role-Based Access Control (RBAC)
On this page
Role-Based Access Control (RBAC) in FastAPI
Published on August 13, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Not every authenticated user should be allowed to do the same things — an ordinary account and an administrator account need different levels of access to the same API, and checking that difference by hand inside every single route quickly turns into scattered, easy-to-miss logic. Role-Based Access Control fixes this by attaching a role to each user once, then enforcing it through a single reusable dependency any route can opt into. Building that layer properly means treating roles as validated, typed values rather than free-form strings, and writing one dependency factory that can enforce any combination of roles rather than a separate function for every one.
What Role-Based Access Control Is
RBAC determines access to a resource by the role assigned to a user, rather than by checking that user's identity directly against a list of permitted individuals. Every user holds a role, every role defines a set of permitted actions, and the API enforces those rules consistently on every request. A typical two-role system looks like this:
RolePermitted actionsuserRead and update their own data, access general featuresadminManage all users, delete records, access analytics and system endpoints
This structure pays off in three concrete ways. Least privilege means a user can only do what their specific role explicitly permits, nothing more. Maintainability means protecting a new route is a one-line addition rather than repeated logic copied into every handler. Auditability means every access decision traces back to a role value stored in the database, rather than to scattered conditional checks that are hard to review as a whole.
Defining Roles as a Typed Enum
Storing a role as a bare string — "admin", "user" — carries no validation at all. A typo like "adnim" or a case mismatch like "Admin" silently creates a value that will never match any check written against it, with no error to flag the mistake. A Python Enum closes that gap:
from sqlmodel import SQLModel, Field
from typing import Optional
from enum import Enum
class Role(str, Enum):
user = "user"
admin = "admin"
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: Role = Role.user
Why a string-based enum
Mixing str into the Enum base class means Role.admin == "admin" evaluates to True directly, which is what lets database storage and JSON serialization work without any manual conversion step — SQLModel stores the plain string value of the enum in the database column, and FastAPI serializes it as a plain string in JSON responses, with no extra code required for either. role: Role = Role.user sets the default at the model level, enforced simultaneously by Python's type system, Pydantic's validation, and the database column default — no code path anywhere in the application can assign a role outside the two defined values without raising a validation error immediately.
Assigning a Default Role at Signup
@router.post("/signup", status_code=201)
def signup(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)
# role defaults to Role.user via the model field — no override needed here
session.add(user)
session.commit()
session.refresh(user)
return {"message": "User created", "user_id": user.id}
Because Role.user is declared as the field's default directly on the model, a new signup gets that role automatically without the route needing to set it explicitly. Creating an admin account happens through one of two paths: a protected PATCH /users/{id}/role endpoint, covered further down, or inserting a role directly during initial setup — for example, in a seed script that runs once when the application is first deployed.
Loading the Current User's Role
get_current_user decodes the JWT, looks up the corresponding user in the database, and returns the full User object — role included — for any downstream dependency to inspect:
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, Role
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
A missing user for an otherwise validly-signed token returns 401, not 404 — a 404 implies a resource that could exist at that address but doesn't right now, while a user deleted after their token was issued means the authentication context itself is no longer valid, which is exactly what 401 communicates. Checking is_active inside get_current_user itself, rather than in each individual route, means every protected route in the system rejects a deactivated account automatically, with no route-specific logic needed to enforce it.
A Reusable Role-Guard Dependency Factory
A dependency factory is a function that accepts one or more allowed roles as arguments and returns a dependency function shaped to enforce exactly those roles — called once when a route is defined, with the returned function being what FastAPI actually injects at request time:
from typing import Callable
def require_roles(*allowed_roles: Role) -> Callable:
"""
Dependency factory that enforces role-based access control.
Usage:
@router.get("/admin/users", dependencies=[Depends(require_roles(Role.admin))])
@router.get("/reports", dependencies=[Depends(require_roles(Role.admin, Role.editor))])
"""
def role_guard(user: User = Depends(get_current_user)) -> User:
if user.role not in allowed_roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Access denied. Required role(s): {', '.join(r.value for r in allowed_roles)}",
)
return user
return role_guard
Why a factory, not one function per role
A system with user, admin, editor, and moderator roles could in principle define a separate function for every role or role combination that needs checking — require_admin, require_editor, require_admin_or_editor — each repeating the same comparison logic against a different set of allowed values. A single factory produces any of those checks from one implementation instead:
Depends(require_roles(Role.admin))
Depends(require_roles(Role.editor))
Depends(require_roles(Role.admin, Role.editor))
Adding an entirely new role to the system requires no new dependency function at all — only a new Role enum value and the appropriate require_roles(...) call at whichever routes need it.
Protecting Routes with Role Guards
An admin-only route
from fastapi import APIRouter, Depends
from sqlmodel import Session, select
from typing import List
from db import get_session
from core.dependencies import require_roles
from models.user import User, Role
from pydantic import BaseModel, ConfigDict
class UserRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
username: str
email: str
is_active: bool
role: Role
router = APIRouter(prefix="/users", tags=["Users"])
@router.get(
"/",
response_model=List[UserRead],
dependencies=[Depends(require_roles(Role.admin))],
)
def list_all_users(session: Session = Depends(get_session)):
return session.exec(select(User)).all()
model_config = ConfigDict(from_attributes=True) is the current Pydantic syntax for allowing UserRead to validate directly from a SQLModel/ORM instance rather than only from a dictionary — a nested class Config: still works but is the deprecated form this replaces. UserRead deliberately excludes hashed_password: returning raw User objects directly from this route would serialize every field on the model, password hash included, straight into the response.
A route open to any authenticated user
from core.dependencies import get_current_user
@router.get("/", dependencies=[Depends(get_current_user)])
def get_tasks(...):
...
Since get_current_user already checks is_active on every call, a plain Depends(get_current_user) is sufficient wherever any active authenticated user — regardless of role — should be allowed through. Narrowing this to specific roles later is a one-line change, swapping in require_roles(Role.admin, Role.editor) in place of get_current_user.
How the Dependency Chain Executes
Request arrives with Bearer token
│
▼
OAuth2PasswordBearer extracts the token string from the Authorization header
│
▼
get_current_user() decodes the JWT → queries the database → checks is_active → returns User
│
▼
require_roles(Role.admin) checks user.role against the allowed roles → raises 403 or passes through
│
▼
Route handler executes, with the caller already confirmed authenticated and authorized
Each layer here has exactly one responsibility: get_current_user handles authentication, require_roles handles authorization, and the route handler handles business logic — none of the three needs to know how the others work internally.
Promoting a User's Role
@router.patch(
"/{user_id}/role",
response_model=UserRead,
dependencies=[Depends(require_roles(Role.admin))],
)
def update_user_role(
user_id: int,
new_role: Role,
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 = new_role
session.add(user)
session.commit()
session.refresh(user)
return user
new_role: Role means FastAPI validates the incoming value against the enum automatically — sending "superadmin" or "ADMIN" produces a 422 Unprocessable Entity before update_user_role's body ever runs, with no manual check needed for that.
A Self-Service Profile Endpoint
@router.get("/me", response_model=UserRead)
def get_current_user_profile(current_user: User = Depends(get_current_user)):
return current_user
Every authenticated user, regardless of role, can reach this route — get_current_user is used here directly as the injected value rather than purely as a pass/fail guard, since the route needs the actual user object to return.
Testing in Swagger UI
Opening /docs allows testing the full access-control layer directly: logging in as a user-role account through POST /auth/login, copying the access token, and pasting it into the "Authorize" button, then calling GET /users/ returns 403 Forbidden with the message Access denied. Required role(s): admin. Logging in as an admin account and repeating the same call returns 200 OK with the full user list, and no hashed_password field present anywhere in the response. GET /users/me succeeds for either account, returning that account's own profile.
RBAC Component Reference
ComponentFilePurposeRole``models/user.py``str enum defining and validating every valid role valuerole fieldmodels/user.pyStores the user's role; defaults to Role.user``get_current_user``core/dependencies.pyAuthenticates the token, checks is_active, returns the User``require_roles(*roles)``core/dependencies.pyFactory returning a role-checking dependency for any combination of rolesUserRead``routers/users.pySafe response schema — excludes hashed_password from every user-facing responsePATCH /users/{id}/role``routers/users.pyAdmin-only endpoint to promote or demote usersGET /users/me``routers/users.pyAny authenticated user's own profile
Security Checklist for RBAC in Production
Returning raw ORM objects from a user-listing route risks leaking sensitive fields; a response_model that explicitly excludes them is what prevents that regardless of what the underlying object actually contains. Storing roles as an enum rather than a bare string catches an invalid value at validation time rather than letting it silently fail every check downstream. Checking is_active inside get_current_user, rather than in individual routes, guarantees coverage from a single place instead of depending on every route author remembering to add the check themselves. A 401 with a WWW-Authenticate: Bearer header on an invalid token follows RFC 6750 and matches what OAuth2 clients expect to see. A 403, by contrast, belongs on a valid token with an insufficient role — the distinction matters: 401 means "the system doesn't know who you are," 403 means "the system knows exactly who you are, and that's not enough." A dependency factory for role guards, rather than a hand-written function per role, is what keeps this whole system extending cleanly as new roles get added.
Key Takeaways
RBAC works by attaching a validated role to each user once, then enforcing that role through a single reusable dependency rather than scattered per-route checks. A str-based Enum gives role values real validation, clean database storage, and clean JSON serialization simultaneously, closing off the typo-prone bare-string approach entirely. get_current_user and require_roles divide authentication and authorization into two distinct, single-purpose dependencies, with the factory pattern behind require_roles letting any combination of roles be enforced from one implementation rather than a new function per role. The distinction between 401 and 403 isn't a stylistic choice — it's the difference between "unauthenticated" and "authenticated but not permitted," and getting it right is part of what makes an access-control layer's responses actually useful to whoever's calling the API.
Practice: Stats, Activation Toggles, and a Moderator Role
An admin-only endpoint aggregating user counts by role:
from sqlmodel import func
@router.get("/stats", dependencies=[Depends(require_roles(Role.admin))])
def get_user_stats(session: Session = Depends(get_session)):
results = session.exec(
select(User.role, func.count(User.id)).group_by(User.role)
).all()
return {role.value: count for role, count in results}
select(User.role, func.count(User.id)).group_by(User.role) runs a single aggregation query rather than fetching every user and counting in Python — for a large table, this is the difference between a database doing the counting efficiently and an application server pulling every row across the network just to tally them.
Admin-only activation toggles:
@router.patch(
"/{user_id}/activate",
response_model=UserRead,
dependencies=[Depends(require_roles(Role.admin))],
)
def activate_user(user_id: int, session: Session = Depends(get_session)):
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
user.is_active = True
session.add(user)
session.commit()
session.refresh(user)
return user
@router.patch(
"/{user_id}/deactivate",
response_model=UserRead,
dependencies=[Depends(require_roles(Role.admin))],
)
def deactivate_user(user_id: int, session: Session = Depends(get_session)):
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
user.is_active = False
session.add(user)
session.commit()
session.refresh(user)
return user
Both routes toggle is_active without touching the user's row otherwise — deactivating an account this way means every future request bearing that user's token fails inside get_current_user's is_active check immediately, without deleting anything or needing to track revoked tokens separately.
A third role demonstrating differentiated access:
class Role(str, Enum):
user = "user"
moderator = "moderator"
admin = "admin"
@router.get(
"/",
response_model=List[UserRead],
dependencies=[Depends(require_roles(Role.admin, Role.moderator))],
)
def list_all_users(session: Session = Depends(get_session)):
return session.exec(select(User)).all()
@router.patch(
"/{user_id}/role",
response_model=UserRead,
dependencies=[Depends(require_roles(Role.admin))],
)
def update_user_role(user_id: int, new_role: Role, session: Session = Depends(get_session)):
...
list_all_users now accepts both admin and moderator through require_roles(Role.admin, Role.moderator), while update_user_role still only accepts require_roles(Role.admin) — a moderator account can view the full user list but gets 403 Forbidden attempting to change anyone's role. Both checks reuse the exact same require_roles implementation with no new logic written for either one, which is the direct payoff of having built the guard as a factory rather than as fixed, single-purpose functions from the start.
Frequently Asked Questions
What is Role-Based Access Control (RBAC) in FastAPI?
RBAC is a security pattern where access to API routes is granted based on the role assigned to the authenticated user, not their identity directly. In FastAPI, it is implemented by storing a role on the User model, decoding the JWT to retrieve the current user, and using dependency injection to check that role before the route handler executes.
Why should I use an Enum for user roles instead of a plain string?
A plain string field accepts any value — typos like "adnim" or case mismatches like "Admin" are stored silently and will never match a role check, causing authorization failures that are hard to debug. A str-based Enum like Role(str, Enum) restricts the field to the declared values only. Any value outside the set raises a Pydantic ValidationError before it reaches the database, making invalid roles impossible at the application layer.
What is a dependency factory in FastAPI and why is it used for RBAC?
A dependency factory is a function that accepts parameters and returns a dependency function. For RBAC, require_roles(*allowed_roles) is the factory — you call it at route definition time with the roles you want to permit, and it returns the actual guard function FastAPI injects at request time. This means one implementation covers any combination of roles, instead of writing a separate function for every role or role combination.
What is the difference between a 401 and a 403 response in an RBAC system?
A 401 Unauthorized means the server cannot identify the caller — the token is missing, malformed, expired, or the user no longer exists. A 403 Forbidden means the server has identified the caller but their role does not permit the action. Returning 403 for a valid token with insufficient role, and 401 for an invalid or missing token, is required by HTTP semantics and helps clients display the correct error to the user.
Why must the WWW-Authenticate: Bearer header be included in 401 responses?
RFC 6750 — the OAuth2 Bearer Token standard — requires that a 401 Unauthorized response include the WWW-Authenticate: Bearer header. OAuth2 clients use this header to detect that Bearer authentication is needed and to trigger the correct re-authentication flow. Omitting it means some clients will not handle the 401 correctly. In FastAPI, it is added via the headers parameter of HTTPException.
Why should is_active be checked in get_current_user rather than in individual routes?
Checking is_active in get_current_user means every single protected route in the application automatically rejects deactivated accounts, with no per-route code. If you check it in individual routes instead, you must remember to add the check every time you write a new protected endpoint. One missed check means a deactivated user can still access that route. Centralizing the check in the authentication dependency makes it impossible to forget.
Why does get_current_user return 401 instead of 404 when the user is not found in the database?
A 404 implies the resource might exist elsewhere or could be created. When a valid JWT contains a username that no longer exists in the database, the token itself has become invalid for authentication purposes — the identity it references is gone. The correct response is 401 Unauthorized, which tells the client that authentication has failed and a new login is required. Returning 404 here would leak information about whether a username ever existed.
How do I protect a FastAPI route so only admins can access it?
Add the require_roles(Role.admin) factory call as a route dependency: @router.get("/admin/users", dependencies=[Depends(require_roles(Role.admin))]). FastAPI will run the dependency before the route handler. If the current user does not hold the Role.admin role, a 403 Forbidden is raised automatically and the handler never executes.
How do I allow multiple roles to access the same route?
Pass multiple roles to the require_roles factory: Depends(require_roles(Role.admin, Role.editor)). The dependency checks whether the current user holds any of the specified roles. If the user has at least one of them, the request proceeds. This requires no additional code beyond listing the roles in the factory call.
Why should I never return raw User ORM objects from a user-listing endpoint?
Raw SQLModel or SQLAlchemy ORM objects include every column in the table, including hashed_password. Even though the hash cannot be reversed, exposing it in API responses is unnecessary and violates the principle of least exposure. Define a UserRead Pydantic schema that includes only the fields clients need — id, username, email, is_active, role — and declare it as the response_model. FastAPI will serialize only those fields, regardless of what the ORM object contains.
What is the execution order of the RBAC dependency chain in FastAPI?
FastAPI resolves dependencies in order from outermost to innermost. For a role-protected route, the chain is: OAuth2PasswordBearer extracts the Bearer token from the Authorization header, then get_current_user decodes the JWT, queries the database, and checks is_active, then require_roles checks the user role against the allowed set, then the route handler executes. If any step fails, FastAPI raises the appropriate HTTP exception and the remaining steps are skipped.
How do I create the first admin user if every admin route is protected?
The first admin must be created outside the API — either by inserting a record directly into the database with role set to "admin" using a seed script that runs at application startup, or by temporarily making the signup endpoint accept a role parameter during initial setup and then removing that capability. Once the first admin exists, the PATCH /users/{id}/role endpoint can be used to promote further users through the API.
How does FastAPI validate the role value in a PATCH /users/{id}/role endpoint?
When the new_role parameter is typed as Role — the str-based Enum — FastAPI automatically validates the incoming value against the enum before the function body runs. If a client sends "superadmin" or "ADMIN", FastAPI returns a 422 Unprocessable Entity with a validation error before any database interaction occurs. This means invalid role values are rejected at the framework level with no manual validation code required.
What is the difference between using dependencies=[] on a route decorator versus Depends() in a function signature?
Both invoke the dependency and enforce its guards. The difference is whether the return value is available in the route handler. Using dependencies=[Depends(require_roles(Role.admin))] in the decorator runs the guard but discards the return value — use this when you only need the side effect of the check. Declaring current_user: User = Depends(get_current_user) in the function signature runs the dependency and makes the returned User object available inside the handler — use this when you need to access the user data.
Can I use RBAC with FastAPI without JWT tokens?
Yes. The role check itself — the require_roles factory and the role field on the User model — is independent of the authentication mechanism. get_current_user can retrieve the current user from an API key, a session cookie, a Basic Auth header, or any other mechanism. The RBAC enforcement layer only depends on having a User object with a role field available. What changes with different authentication methods is how get_current_user obtains that User object, not how roles are checked.
Why is Role defined as str, Enum rather than just Enum in SQLModel?
SQLModel uses Pydantic under the hood for validation and serialization. A plain Enum stores Python enum objects, which require explicit conversion to strings for database storage and JSON serialization. A str-based enum — class Role(str, Enum) — means each value IS a string, so Role.admin == "admin" is True. SQLModel stores the string value directly in the column, FastAPI serializes it as a plain string in JSON responses, and comparisons against database string values work without any conversion code.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
JWT Authentication
Next
API Security Best Practices
-
What Role-Based Access Control Is
-
Defining Roles as a Typed Enum
- Why a string-based enum
-
Assigning a Default Role at Signup
-
Loading the Current User's Role
-
A Reusable Role-Guard Dependency Factory
- Why a factory, not one function per role
-
Protecting Routes with Role Guards
- An admin-only route
- A route open to any authenticated user
-
How the Dependency Chain Executes
-
Promoting a User's Role
-
A Self-Service Profile Endpoint
-
Testing in Swagger UI
-
RBAC Component Reference
-
Security Checklist for RBAC in Production
-
Key Takeaways
-
Practice: Stats, Activation Toggles, and a Moderator Role
-
Frequently Asked Questions
