Role-based access control helps decide who can do what in your app. It keeps things safe by letting only the right people access certain parts.
0
0
Role-based access control in FastAPI
Introduction
You want to let only admins change settings.
You want users to see only their own data.
You want to hide some pages from regular users.
You want to give different permissions to managers and staff.
Syntax
FastAPI
from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def get_current_user(token: str = Depends(oauth2_scheme)): # decode token and return user info pass def role_required(role: str): async def role_checker(user = Depends(get_current_user)): if role not in user.roles: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions") return user return role_checker app = FastAPI() @app.get("/admin") async def read_admin_data(user = Depends(role_required("admin"))): return {"msg": "Welcome admin!"}
Use Depends to check user roles before running endpoint code.
Define a function that returns a dependency checking the role.
Examples
This creates a reusable role checker for any role you want.
FastAPI
def role_required(role: str): async def role_checker(user = Depends(get_current_user)): if role not in user.roles: raise HTTPException(status_code=403, detail="Forbidden") return user return role_checker
This endpoint only lets users with the 'manager' role access it.
FastAPI
@app.get("/manager") async def manager_data(user = Depends(role_required("manager"))): return {"msg": "Hello manager!"}
Sample Program
This example shows a simple way to check user roles using tokens. Admins can access the /admin route, while all logged-in users can access /user.
FastAPI
from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer from typing import List app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class User: def __init__(self, username: str, roles: List[str]): self.username = username self.roles = roles # Fake token to user mapping fake_users_db = { "token_admin": User("alice", ["admin", "user"]), "token_user": User("bob", ["user"]) } async def get_current_user(token: str = Depends(oauth2_scheme)): user = fake_users_db.get(token) if not user: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials") return user def role_required(role: str): async def role_checker(user: User = Depends(get_current_user)): if role not in user.roles: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions") return user return role_checker @app.get("/admin") async def read_admin_data(user: User = Depends(role_required("admin"))): return {"message": f"Welcome admin {user.username}!"} @app.get("/user") async def read_user_data(user: User = Depends(get_current_user)): return {"message": f"Hello user {user.username}!"}
OutputSuccess
Important Notes
Always check user roles after verifying their identity.
Use HTTP 403 status code when access is denied due to roles.
Keep role checks reusable by creating a function that returns a dependency.
Summary
Role-based access control limits what users can do based on their roles.
FastAPI uses dependencies to check roles before running endpoint code.
Creating reusable role checkers keeps your code clean and safe.