
When building a backend application, authentication is usually one of the first things we implement. We create a login endpoint, verify user credentials, generate a JWT token, and protect private routes. But authentication alone is not enough for a production application.
Imagine you're building a SaaS dashboard with three types of users: an admin, a manager, and a regular employee. All three users can log in successfully, but should they have access to the same features?
Probably not.
An admin might be able to manage users, delete records, and change application settings. A manager might be allowed to view reports and update team information. A regular employee might only be able to access their own profile and assigned tasks.
This is where Role-Based Access Control (RBAC) becomes useful.
In this article, we'll implement RBAC in FastAPI using Python, JWT authentication, and dependency injection. We'll start with a simple role-checking mechanism and gradually improve it with reusable dependencies, database integration considerations, and production security practices.
What Is Role-Based Access Control (RBAC)?
Role-Based Access Control is an authorization model in which permissions are assigned to roles, and users receive permissions through the roles assigned to them.
Instead of checking individual users throughout your application, you define roles such as:
Admin: Can manage users, settings, and application resources.
Manager: Can view reports and manage team resources.
User: Can access regular application features.
Viewer: Can read information but cannot modify it.
For example, consider an employee management application.
Feature | Admin | Manager | User |
|---|---|---|---|
View employee records | Yes | Yes | Limited |
Create employee records | Yes | Yes | No |
Update employee records | Yes | Team members only | Own profile only |
Delete employee records | Yes | No | No |
Manage application settings | Yes | No | No |
Without RBAC, developers often end up writing authorization checks directly inside individual route handlers. As the application grows, this approach becomes difficult to maintain.
With RBAC, we can centralize authorization logic and reuse it across multiple endpoints.
Authentication vs Authorization
Before implementing RBAC, it's important to understand the difference between authentication and authorization.
Authentication answers: "Who are you?"
For example, a user provides an email address and password. The backend verifies the credentials and issues an access token.
Authorization answers: "What are you allowed to do?"
After authentication, the backend checks whether the authenticated user has permission to perform a particular action.
Consider this request:
DELETE /api/users/25
Authorization: Bearer <access_token>The token might belong to a valid, authenticated user. However, if that user has the user role instead of the admin role, the backend should reject the request.
A successful login does not automatically grant access to every endpoint.
In FastAPI, we can implement authentication and authorization using dependencies. This makes it possible to validate the current user once and reuse the same authorization rules throughout the application.
Step 1: Install the Required Dependencies
Let's build a small FastAPI application that demonstrates role-based authorization.
We'll use JWT tokens for authentication and FastAPI's dependency injection system to enforce roles.
Install the required packages:
pip install fastapi uvicorn pyjwt pwdlib[argon2]Here's what each package does:
fastapi: Provides the API framework and dependency injection.uvicorn: Runs the FastAPI application.pyjwt: Creates and validates JWT tokens.pwdlib[argon2]: Hashes passwords securely using Argon2.
For this example, we'll use in-memory user data to focus on the RBAC implementation. In a production application, users and their roles should normally be stored in a database.
Step 2: Define User Roles
The first step is to define the roles supported by our application.
Python's Enum is a good choice because it gives us a consistent set of allowed role values.
Create a file named main.py:
from enum import Enum
class UserRole(str, Enum):
ADMIN = "admin"
MANAGER = "manager"
USER = "user"Using an enum helps prevent inconsistent role names such as "Admin", "ADMIN", and "admin" from being treated as different values accidentally.
We can now assign these roles to users and check them inside our endpoints.
For example:
role = UserRole.ADMIN
print(role.value)
# adminFor a small application, these three roles might be enough. A larger application may need additional roles, such as support agents, finance managers, or read-only users.
The important point is to define roles according to actual business requirements rather than creating unnecessary roles for every individual feature.
Step 3: Create a User Model
Next, let's define the structure of a user.
For this demonstration, we'll use Pydantic models.
from pydantic import BaseModel
class User(BaseModel):
id: int
username: str
role: UserRole
is_active: bool = TrueEach user contains:
id: Unique user identifier.username: User's username.role: Assigned authorization role.is_active: Whether the account is active.
Let's create a few sample users:
users_db = {
"admin": User(
id=1,
username="admin",
role=UserRole.ADMIN,
),
"manager": User(
id=2,
username="manager",
role=UserRole.MANAGER,
),
"employee": User(
id=3,
username="employee",
role=UserRole.USER,
),
}This dictionary is only a temporary substitute for a database. It does not provide persistent storage, password verification, or safe concurrent user management.
We'll add JWT authentication next so that our API can identify the user making each request.
Step 4: Implement JWT Authentication
RBAC needs a reliable way to identify the current user.
JWT access tokens are commonly used for this purpose. After validating a user's credentials, the server issues a signed token. The client sends that token with subsequent requests.
Let's define our JWT configuration:
import os
import jwt
from datetime import datetime, timedelta, timezone
from fastapi import HTTPException, status
SECRET_KEY = os.environ["JWT_SECRET_KEY"]
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30Set the secret key through an environment variable rather than hardcoding it in your source code.
For local development, you can generate a random secret using Python:
python -c "import secrets; print(secrets.token_urlsafe(48))"Set the generated value in your environment before starting the application:
export JWT_SECRET_KEY="your-generated-secret"Avoid committing the secret to Git or exposing it in frontend code.
Now, create a function that generates access tokens:
def create_access_token(user: User) -> str:
now = datetime.now(timezone.utc)
payload = {
"sub": str(user.id),
"role": user.role.value,
"iat": now,
"exp": now + timedelta(
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
),
}
return jwt.encode(
payload,
SECRET_KEY,
algorithm=ALGORITHM,
)The token contains three important claims:
sub: The user's identifier.iat: When the token was issued.exp: When the token expires.
We've included the role for demonstration purposes. However, a role embedded in a JWT can become outdated if the user's permissions change before the token expires.
For applications that need immediate role revocation, the server should check the current role from a trusted database or use a carefully designed token-revocation strategy.
Now let's validate incoming tokens.
from fastapi import Depends
from fastapi.security import (
OAuth2PasswordBearer,
)
from jwt.exceptions import InvalidTokenError
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="/token"
)
def get_current_user(
token: str = Depends(oauth2_scheme),
) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(
token,
SECRET_KEY,
algorithms=[ALGORITHM],
)
user_id = payload.get("sub")
if user_id is None:
raise credentials_exception
except InvalidTokenError:
raise credentials_exception
user = next(
(
item
for item in users_db.values()
if str(item.id) == user_id
),
None,
)
if user is None or not user.is_active:
raise credentials_exception
return userThis dependency validates the JWT, retrieves the user, and rejects requests from unknown or inactive accounts.
Notice that we retrieve the user's role from the server-side user record rather than trusting the role claim in the token.
This approach means that changes to a user's role can take effect on the next request, provided the database-backed user record is refreshed on each request.
For a real application, replace the in-memory lookup with a database query.
Step 5: Build a Reusable RBAC Dependency
Now we can implement the main part of RBAC.
Instead of writing the same role-checking condition in every endpoint, we'll create a reusable dependency.
from collections.abc import Callable
from fastapi import Depends, HTTPException, status
def require_roles(
*allowed_roles: UserRole,
) -> Callable:
def role_checker(
current_user: User = Depends(
get_current_user
),
) -> User:
if current_user.role not in allowed_roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You do not have permission "
"to perform this action",
)
return current_user
return role_checkerLet's understand what's happening.
The require_roles() function accepts one or more allowed roles. It returns a dependency that retrieves the current user and checks whether the user's role is included in the allowed roles.
For example:
Depends(require_roles(UserRole.ADMIN))This allows only administrators to access an endpoint.
We can also allow multiple roles:
Depends(
require_roles(
UserRole.ADMIN,
UserRole.MANAGER,
)
)In this case, both administrators and managers can access the endpoint.
The dependency returns the authenticated user when authorization succeeds. If the role does not match, FastAPI raises an HTTP exception with status code 403 Forbidden.
This keeps authorization logic separate from business logic and makes the code easier to test.
Step 6: Protect API Endpoints Using RBAC
Let's create three endpoints with different access rules.
An administrator can view all users, an administrator or manager can access reports, and any authenticated user can access their own profile.
from fastapi import FastAPI, Depends
app = FastAPI()
@app.get("/api/profile")
def get_profile(
current_user: User = Depends(
get_current_user
),
):
return {
"id": current_user.id,
"username": current_user.username,
"role": current_user.role.value,
}
@app.get("/api/users")
def get_users(
current_user: User = Depends(
require_roles(UserRole.ADMIN)
),
):
return [
user.model_dump()
for user in users_db.values()
]
@app.get("/api/reports")
def get_reports(
current_user: User = Depends(
require_roles(
UserRole.ADMIN,
UserRole.MANAGER,
)
),
):
return {
"message": "Reports retrieved successfully",
"requested_by": current_user.username,
}Let's look at the access rules.
Endpoint | Admin | Manager | User |
|---|---|---|---|
| Allowed | Allowed | Allowed |
| Allowed | Denied | Denied |
| Allowed | Allowed | Denied |
An unauthenticated request is rejected before the role check runs.
An authenticated user without the required role receives 403 Forbidden.
This is the main advantage of reusable RBAC dependencies: you can add authorization rules without duplicating the same logic throughout your application.
Step 7: Implement a Login Endpoint
So far, we've created a token-generation function, but we haven't implemented the endpoint that issues tokens.
Let's add a simple login flow.
First, create a password hashing configuration and some sample credentials.
from pwdlib import PasswordHash
password_hash = PasswordHash.recommended()
demo_credentials = {
"admin": password_hash.hash("AdminDemo123!"),
"manager": password_hash.hash("ManagerDemo123!"),
"employee": password_hash.hash("EmployeeDemo123!"),
}These credentials are for local demonstration only. Never use these fixed passwords in production.
Define the request model:
from pydantic import BaseModel
class LoginRequest(BaseModel):
username: str
password: strNow add the login endpoint:
from fastapi import HTTPException, status
@app.post("/token")
def login(data: LoginRequest):
user = users_db.get(data.username)
stored_hash = demo_credentials.get(data.username)
if (
user is None
or stored_hash is None
or not password_hash.verify(
data.password,
stored_hash,
)
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(user)
return {
"access_token": access_token,
"token_type": "bearer",
"expires_in": ACCESS_TOKEN_EXPIRE_MINUTES * 60,
}This example demonstrates the basic login flow:
Receive the username and password.
Retrieve the corresponding user and password hash.
Verify the password.
Generate a signed JWT if the credentials are valid.
Return the token to the client.
In a real application, store password hashes alongside user records in your database. Add login rate limiting, secure password-reset functionality, and appropriate monitoring for repeated failed attempts.
Also remember that the example's in-memory user data is intended for learning, not production deployment.
Step 8: Test RBAC Using Swagger UI
FastAPI automatically generates interactive API documentation.
Start the application:
uvicorn main:app --reloadOpen the Swagger UI in your browser:
http://127.0.0.1:8000/docsYou can test the API using the following workflow.
Test 1: Log in as an administrator
Send a POST request to /token:
{
"username": "admin",
"password": "AdminDemo123!"
}The response includes an access token.
Test 2: Access the protected users endpoint
Authorize Swagger UI using the returned bearer token, then call:
GET /api/usersThe request should succeed because the current user has the admin role.
Test 3: Log in as an employee
Use these demonstration credentials:
{
"username": "employee",
"password": "EmployeeDemo123!"
}Call /api/users using the employee's token.
The server should return:
{
"detail": "You do not have permission to perform this action"
}The HTTP status code is 403 Forbidden.
Test 4: Try the reports endpoint
The employee should receive 403 Forbidden, while the manager and administrator should be able to access the reports endpoint.
These tests demonstrate that successful authentication does not automatically grant access to every resource.
Step 9: Store Roles in a Database
An in-memory user dictionary is useful for understanding the concept, but production applications need persistent storage.
For example, a PostgreSQL database might use a users table:
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
username VARCHAR(100) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role VARCHAR(20) NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT valid_user_role
CHECK (role IN ('admin', 'manager', 'user'))
);This schema stores each user's role alongside their account information.
For a simple application, a single role column can be sufficient.
However, a larger application may require multiple roles per user, configurable permissions, or organization-specific roles. In that situation, a normalized schema is more flexible.
For example:
users
-----
id
username
password_hash
is_active
roles
-----
id
name
permissions
-----------
id
name
user_roles
----------
user_id
role_id
role_permissions
----------------
role_id
permission_idThis structure separates users, roles, and permissions.
A user can have multiple roles, and each role can contain multiple permissions.
For example, the manager role might include:
reports:read
employees:read
employees:updateThe admin role might include:
users:read
users:create
users:update
users:delete
settings:updateYour authorization dependency can then check permissions rather than relying exclusively on hardcoded role names.
This becomes particularly useful when building SaaS applications where different customers may need different access policies.
Step 10: Understand Role-Based and Permission-Based Access
Role checks work well when access rules are relatively simple.
For example:
Depends(require_roles(UserRole.ADMIN))But consider an application where managers can update employees only within their own department.
A role check alone cannot enforce that rule.
The backend also needs to verify that the requested employee belongs to the manager's department.
This is where resource-level authorization becomes important.
For example:
@app.put("/api/employees/{employee_id}")
def update_employee(
employee_id: int,
current_user: User = Depends(
require_roles(
UserRole.ADMIN,
UserRole.MANAGER,
)
),
):
employee = get_employee_from_database(
employee_id
)
if employee is None:
raise HTTPException(
status_code=404,
detail="Employee not found",
)
if current_user.role == UserRole.MANAGER:
if (
employee.department_id
!= current_user.department_id
):
raise HTTPException(
status_code=403,
detail="You cannot update employees "
"outside your department",
)
return update_employee_record(employee)The functions and department fields in this example represent application-specific database operations and models; they must be implemented before this endpoint can run.
The authorization logic follows two stages:
Check whether the user has an allowed role.
Check whether the user is allowed to modify the specific resource.
This distinction is important. A manager may be allowed to update employee records generally, but that doesn't mean they should be allowed to update every employee in the organization.
For more complex systems, consider combining RBAC with attribute-based access control (ABAC), which evaluates attributes such as department, ownership, organization, or resource state.
Step 11: Common RBAC Security Mistakes
Implementing role checks is straightforward. Implementing them securely across an entire application requires more care.
Here are some mistakes to avoid.
1. Trusting the Role Sent by the Client
Never authorize a request based on a role supplied directly in the request body or query parameters.
For example, this is unsafe:
@app.delete("/api/users/{user_id}")
def delete_user(
user_id: int,
role: str,
):
if role == "admin":
# Delete the user
passAnyone could send role=admin.
Instead, derive the current user's identity from a validated access token and load their current authorization information from a trusted server-side source.
2. Checking Roles Only in the Frontend
You might hide an admin button in React:
{user.role === "admin" && (
<button>Delete User</button>
)}This improves the user interface, but it does not protect your backend.
A user can call the API directly using a browser console, Postman, or a custom script.
Every sensitive operation must be authorized on the server.
3. Returning the Wrong HTTP Status Code
Use the appropriate status code for each situation:
401 Unauthorized: Authentication is missing or invalid.403 Forbidden: The user is authenticated but lacks the required permission.
Correct status codes help frontend applications handle authorization failures consistently.
4. Forgetting to Check Account Status
A disabled account should not retain access simply because it previously received a valid token.
Check the user's current account status during authentication or authorization, according to your application's security requirements.
5. Ignoring Role Changes
Suppose an administrator changes an employee's role from admin to user.
If the backend blindly trusts a role claim inside a long-lived JWT, the employee might retain administrator privileges until the token expires.
Possible solutions include:
Loading current role information from the database.
Using short-lived access tokens.
Maintaining token versions or revocation records.
Invalidating sessions when sensitive permissions change.
Choose an approach based on your application's security requirements and expected traffic.
6. Applying Authorization Inconsistently
Protecting a single route does not secure every endpoint.
For example, an application might protect DELETE /api/users/{id} but forget to protect another endpoint that performs the same deletion indirectly.
Review all routes that access sensitive resources, including background jobs and administrative operations. Write automated tests to verify authorization for every important action.
Step 12: Test RBAC Automatically
Manual testing is useful during development, but authorization rules should also be covered by automated tests.
FastAPI provides a TestClient that makes it straightforward to test API behavior.
For example:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_profile_requires_authentication():
response = client.get("/api/profile")
assert response.status_code == 401
def test_admin_can_access_users():
login_response = client.post(
"/token",
json={
"username": "admin",
"password": "AdminDemo123!",
},
)
token = login_response.json()["access_token"]
response = client.get(
"/api/users",
headers={
"Authorization": f"Bearer {token}"
},
)
assert response.status_code == 200
def test_employee_cannot_access_users():
login_response = client.post(
"/token",
json={
"username": "employee",
"password": "EmployeeDemo123!",
},
)
token = login_response.json()["access_token"]
response = client.get(
"/api/users",
headers={
"Authorization": f"Bearer {token}"
},
)
assert response.status_code == 403Install the testing dependencies if needed:
pip install pytest httpxRun the tests:
pytestThese tests cover three important scenarios: unauthenticated access, successful administrator access, and denied employee access.
In a production project, expand the test suite to cover every role, disabled accounts, expired tokens, malformed tokens, resource ownership, and role changes.
For database-backed applications, use a test database and isolate test data so that tests remain repeatable.
Step 13: Production Best Practices for FastAPI RBAC
Before deploying an RBAC implementation, keep the following practices in mind.
Keep authorization logic reusable. Put role and permission checks in dedicated dependencies or authorization services instead of duplicating them across route handlers.
Use least privilege. Give users only the permissions they need to perform their work. Avoid assigning administrator privileges by default.
Separate authentication from authorization. Authentication identifies the user; authorization decides whether that user can perform an action.
Validate resource ownership. A user should not be able to access another user's private data merely because they have a valid token.
Use database constraints. Ensure that role assignments and relationships remain consistent. Validate role values at the application and database levels where appropriate.
Protect sensitive administrative actions. Consider audit logs that record who performed an action, what resource was affected, and when the action occurred. Avoid logging passwords, access tokens, or other secrets.
Keep access tokens short-lived. Choose an appropriate expiration period and implement a refresh or reauthentication strategy when needed.
Avoid unnecessary database queries. Load user and permission information efficiently. If you introduce caching, define how permission changes invalidate cached authorization data.
Review authorization when adding routes. New endpoints should have explicit access rules, and automated tests should verify them.
Document your access model. Maintain a clear description of roles, permissions, and sensitive operations so that developers can understand and review authorization decisions.
Conclusion
Role-Based Access Control is an important part of building secure backend applications. Authentication confirms who the user is, while RBAC determines which operations that user can perform.
FastAPI makes RBAC relatively straightforward through its dependency injection system. By creating a reusable require_roles() dependency, we can protect endpoints without repeating authorization logic in every route handler.
For small applications, a few predefined roles may be enough. For larger SaaS platforms, a database-backed permission model with resource-level authorization provides more flexibility.
The most important lesson is that authorization must be enforced by the backend on every sensitive operation. Hiding buttons in the frontend, trusting client-supplied roles, or relying on outdated token claims is not enough.
Start with a clear set of roles, centralize authorization checks, validate resource access, and write tests for both allowed and denied requests. These practices provide a solid foundation for building secure FastAPI applications that can grow with your product.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


