0
0
FastAPIframework~10 mins

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

Choose your learning style9 modes available
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.