Bird
Raised Fist0
FastAPIframework~10 mins

Role-based access control in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Role-based access control
User sends request
Extract user role from token
Check if role allowed for endpoint
Allow access
Execute endpoint
The flow shows how FastAPI checks a user's role from their token and allows or denies access to an endpoint based on that role.
Execution Sample
FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user_role(token: str = Depends(oauth2_scheme)):
    # Simulate decoding token to get role
    if token == "admin-token":
        return "admin"
    elif token == "user-token":
        return "user"
    else:
        raise HTTPException(status_code=401, detail="Invalid token")

async def role_checker(required_role: str):
    async def checker(role: str = Depends(get_current_user_role)):
        if role != required_role:
            raise HTTPException(status_code=403, detail="Access forbidden")
    return checker

@app.get("/admin")
async def admin_endpoint(dep=Depends(role_checker("admin"))):
    return {"message": "Welcome admin!"}
This code checks the user's role from a token and only allows access to the /admin endpoint if the role is 'admin'.
Execution Table
StepActionTokenExtracted RoleRole CheckResult
1Request to /admin with token 'admin-token'admin-tokenadminadmin == admin?Allow access
2Execute admin_endpointadmin-tokenadminN/AReturn message 'Welcome admin!'
3Request to /admin with token 'user-token'user-tokenuseruser == admin?Deny access 403
4Request to /admin with token 'invalid-token'invalid-tokenNoneToken invalidDeny access 401
💡 Access is allowed only if the extracted role matches the required role; otherwise, request is denied.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4
tokenNoneadmin-tokenuser-tokeninvalid-token
roleNoneadminuserNone
access_allowedFalseTrueFalseFalse
Key Moments - 2 Insights
Why does the request with 'user-token' get denied access to /admin?
Because in the execution_table row 3, the extracted role is 'user' which does not match the required 'admin' role, so access is denied with 403.
What happens if the token is invalid or missing?
As shown in execution_table row 4, the token cannot be decoded to a role, so a 401 Unauthorized error is returned before role checking.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the extracted role at step 1?
ANone
Badmin
Cuser
Dguest
💡 Hint
Check the 'Extracted Role' column in execution_table row 1.
At which step does the role check fail and deny access?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for 'Deny access 403' in the 'Result' column of execution_table.
If the token was 'admin-token' but the required role was 'user', what would happen?
AAccess denied with 403
BAccess allowed
CAccess denied with 401
DServer error
💡 Hint
Role must match required role exactly; see role check logic in execution_table.
Concept Snapshot
Role-based access control in FastAPI:
- Extract user role from token using Depends
- Use a role checker dependency to compare roles
- If roles match, allow endpoint access
- Otherwise, raise 403 Forbidden
- Invalid tokens raise 401 Unauthorized
Full Transcript
This example shows how FastAPI uses role-based access control by extracting a user's role from a token and checking it against the required role for an endpoint. If the roles match, the user can access the endpoint; if not, access is denied with a 403 error. Invalid tokens cause a 401 error. The execution table traces requests with different tokens, showing how roles are extracted and checked step-by-step.

Practice

(1/5)
1. What is the main purpose of role-based access control (RBAC) in FastAPI?
easy
A. To speed up API response times
B. To limit user actions based on their assigned roles
C. To automatically generate API documentation
D. To handle database migrations

Solution

  1. Step 1: Understand RBAC concept

    RBAC restricts what users can do depending on their roles, like admin or user.
  2. Step 2: Identify RBAC purpose in FastAPI

    FastAPI uses RBAC to check user roles before allowing access to certain endpoints.
  3. Final Answer:

    To limit user actions based on their assigned roles -> Option B
  4. Quick Check:

    RBAC = limit actions by roles [OK]
Hint: RBAC controls user permissions by roles, not speed or docs [OK]
Common Mistakes:
  • Confusing RBAC with performance optimization
  • Thinking RBAC auto-generates docs
  • Assuming RBAC manages database tasks
2. Which of the following is the correct way to declare a dependency that checks for an admin role in FastAPI?
easy
A. def admin_required(user: User = Depends(get_current_user)): if user.role == 'guest': raise HTTPException(status_code=401)
B. def admin_required(user: User): if user.role == 'admin': return True
C. def admin_required(): return 'admin' in user.roles
D. def admin_required(user: User = Depends(get_current_user)): if user.role != 'admin': raise HTTPException(status_code=403)

Solution

  1. Step 1: Check dependency signature

    def admin_required(user: User = Depends(get_current_user)): if user.role != 'admin': raise HTTPException(status_code=403) uses Depends to get current user, which is required for role checking.
  2. Step 2: Verify role check logic

    def admin_required(user: User = Depends(get_current_user)): if user.role != 'admin': raise HTTPException(status_code=403) raises HTTP 403 if user is not admin, correctly enforcing access control.
  3. Final Answer:

    def admin_required(user: User = Depends(get_current_user)): if user.role != 'admin': raise HTTPException(status_code=403) -> Option D
  4. Quick Check:

    Depends + role check + HTTPException = def admin_required(user: User = Depends(get_current_user)): if user.role != 'admin': raise HTTPException(status_code=403) [OK]
Hint: Use Depends to get user, then check role and raise HTTPException [OK]
Common Mistakes:
  • Not using Depends to get current user
  • Checking wrong role or missing exception
  • Returning True instead of raising exception
3. Given this FastAPI endpoint with role check dependency:
async def get_admin_data(admin: None = Depends(admin_required)):
    return {"data": "secret"}
What happens if a user with role 'user' calls this endpoint?
medium
A. The endpoint raises HTTP 403 Forbidden error
B. The endpoint returns {"data": "secret"}
C. The endpoint raises HTTP 401 Unauthorized error
D. The endpoint returns an empty response

Solution

  1. Step 1: Understand admin_required behavior

    admin_required raises HTTP 403 if user role is not 'admin'.
  2. Step 2: Apply to user role 'user'

    User role 'user' is not 'admin', so HTTP 403 is raised before endpoint runs.
  3. Final Answer:

    The endpoint raises HTTP 403 Forbidden error -> Option A
  4. Quick Check:

    Non-admin user triggers 403 error [OK]
Hint: Non-admin roles cause 403 error before endpoint runs [OK]
Common Mistakes:
  • Confusing 401 Unauthorized with 403 Forbidden
  • Expecting endpoint to return data for non-admin
  • Thinking empty response is returned
4. Identify the error in this FastAPI role check dependency:
def check_admin(user: User = Depends(get_current_user)):
    if user.role == 'admin':
        return True
    else:
        return False

@app.get('/admin')
async def admin_panel(is_admin: bool = Depends(check_admin)):
    if not is_admin:
        raise HTTPException(status_code=403)
    return {"msg": "Welcome admin"}
medium
A. Dependency should raise HTTPException directly, not return bool
B. Depends should not be used inside dependency functions
C. The endpoint should not check is_admin, dependency handles it
D. The function should return user object, not bool

Solution

  1. Step 1: Analyze dependency behavior

    check_admin returns True/False instead of raising HTTPException on failure.
  2. Step 2: Understand best practice for RBAC in FastAPI

    Dependencies should raise HTTPException to stop execution early, not return bool flags.
  3. Final Answer:

    Dependency should raise HTTPException directly, not return bool -> Option A
  4. Quick Check:

    Raise exception in dependency, don't return bool [OK]
Hint: Raise HTTPException in dependency to block access immediately [OK]
Common Mistakes:
  • Returning bool instead of raising exception
  • Not stopping request early in dependency
  • Misusing Depends inside dependencies
5. You want to create a reusable role checker in FastAPI that allows multiple roles (e.g., 'admin' or 'moderator') to access an endpoint. Which approach correctly implements this?
hard
A. def role_checker(user: User = Depends(get_current_user)): if user.role == 'admin' and user.role == 'moderator': return True raise HTTPException(status_code=403)
B. def role_checker(user: User = Depends(get_current_user)): if user.role != 'admin' or user.role != 'moderator': raise HTTPException(status_code=403)
C. def role_checker(allowed_roles: list[str]): def checker(user: User = Depends(get_current_user)): if user.role not in allowed_roles: raise HTTPException(status_code=403) return checker
D. def role_checker(allowed_roles: list[str]): for role in allowed_roles: if role == user.role: return True return False

Solution

  1. Step 1: Understand reusable dependency pattern

    def role_checker(allowed_roles: list[str]): def checker(user: User = Depends(get_current_user)): if user.role not in allowed_roles: raise HTTPException(status_code=403) return checker returns a function that checks if user role is in allowed_roles, raising HTTPException if not.
  2. Step 2: Verify logic for multiple roles

    def role_checker(allowed_roles: list[str]): def checker(user: User = Depends(get_current_user)): if user.role not in allowed_roles: raise HTTPException(status_code=403) return checker correctly uses 'not in' to allow any role in the list, making it reusable.
  3. Final Answer:

    def role_checker(allowed_roles: list[str]): def checker(user: User = Depends(get_current_user)): if user.role not in allowed_roles: raise HTTPException(status_code=403) return checker -> Option C
  4. Quick Check:

    Reusable role check with allowed_roles list = def role_checker(allowed_roles: list[str]): def checker(user: User = Depends(get_current_user)): if user.role not in allowed_roles: raise HTTPException(status_code=403) return checker [OK]
Hint: Return inner function checking role in allowed_roles, raise HTTPException [OK]
Common Mistakes:
  • Using incorrect logic with 'or' instead of 'in'
  • Returning bool instead of raising exception
  • Checking impossible conditions like role == 'admin' and 'moderator'