0
0
FastAPIframework~20 mins

Role-based access control in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Role-based Access Control Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when accessing a protected route with insufficient role?

Consider a FastAPI route protected by a dependency that checks if the user has the 'admin' role. If a user with only the 'user' role tries to access it, what will be the HTTP response status code?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

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

fake_users_db = {
    "alice": {"username": "alice", "roles": ["user"]},
    "bob": {"username": "bob", "roles": ["admin"]}
}

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")
    return user

def require_admin(user: dict = Depends(get_current_user)):
    if "admin" not in user["roles"]:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions")
    return user

@app.get("/admin")
async def read_admin_data(user: dict = Depends(require_admin)):
    return {"msg": "Welcome admin!"}
AHTTP 403 Forbidden error
BHTTP 200 with message 'Welcome admin!'
CHTTP 401 Unauthorized error
DHTTP 404 Not Found error
Attempts:
2 left
💡 Hint

Think about what happens when the user is authenticated but lacks the required role.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly implements role checking in FastAPI dependency?

Choose the code snippet that correctly checks if the current user has the 'editor' role and raises a 403 error if not.

A
def require_editor(user: dict = Depends(get_current_user)):
    if user.roles != ['editor']:
        raise HTTPException(status_code=403, detail='Forbidden')
    return user
B
def require_editor(user: dict = Depends(get_current_user)):
    if 'editor' not in user['roles']:
        raise HTTPException(status_code=403, detail='Forbidden')
    return user
C
def require_editor(user: dict = Depends(get_current_user)):
    if 'editor' not in user.roles:
        raise HTTPException(status_code=403, detail='Forbidden')
    return user
D
def require_editor(user: dict = Depends(get_current_user)):
    if user['roles'] != 'editor':
        raise HTTPException(status_code=403, detail='Forbidden')
    return user
Attempts:
2 left
💡 Hint

Remember that roles are stored as a list inside a dictionary.

state_output
advanced
2:00remaining
What is the response when a user with multiple roles accesses a route requiring one role?

Given a user with roles ['user', 'editor'] accessing a route protected by a dependency that requires the 'editor' role, what will be the response?

FastAPI
from fastapi import FastAPI, Depends, HTTPException, status

app = FastAPI()

fake_users_db = {
    "carol": {"username": "carol", "roles": ["user", "editor"]}
}

def get_current_user(token: str):
    user = fake_users_db.get(token)
    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    return user

def require_editor(user: dict = Depends(get_current_user)):
    if "editor" not in user["roles"]:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
    return user

@app.get("/edit")
async def edit_content(user: dict = Depends(require_editor)):
    return {"msg": f"Hello {user['username']}, you can edit content."}
AHTTP 403 Forbidden error
BHTTP 401 Unauthorized error
CHTTP 404 Not Found error
D{"msg": "Hello carol, you can edit content."}
Attempts:
2 left
💡 Hint

Check if the required role is present in the user's roles list.

🔧 Debug
advanced
2:00remaining
Identify the error in this role check dependency

What error will this FastAPI dependency raise when called?

FastAPI
def require_admin(user: dict = Depends(get_current_user)):
    if user['roles'] != 'admin':
        raise HTTPException(status_code=403, detail='Forbidden')
    return user
AAlways raises HTTP 403 even if user has 'admin' role
BRaises KeyError because 'roles' key is missing
CRaises TypeError due to wrong comparison
DReturns user correctly if 'admin' role is present
Attempts:
2 left
💡 Hint

Consider the data type of user['roles'] and what the comparison checks.

🧠 Conceptual
expert
2:00remaining
Why use dependencies for role-based access control in FastAPI?

Which is the best explanation for why FastAPI uses dependencies to implement role-based access control?

ADependencies force all routes to require admin role by default, simplifying security.
BDependencies automatically encrypt user roles to secure them from tampering.
CDependencies allow reusable, modular checks that run before route logic, enabling clean separation of authorization concerns.
DDependencies replace the need for authentication by verifying user identity through roles alone.
Attempts:
2 left
💡 Hint

Think about how dependencies help organize code and enforce checks.