Bird
0
0

How can you combine FastAPI's protected routes with role-based access control (RBAC) to restrict access to admin users only?

hard🧠 Conceptual Q9 of 15
FastAPI - Authentication and Security
How can you combine FastAPI's protected routes with role-based access control (RBAC) to restrict access to admin users only?
AExtract token with OAuth2PasswordBearer, decode user roles, and raise HTTPException if role is not 'admin'
BUse OAuth2PasswordBearer and allow all roles without checks
CSkip token extraction and check roles from query parameters
DUse OAuth2PasswordBearer and return all users regardless of role
Step-by-Step Solution
Solution:
  1. Step 1: Use OAuth2PasswordBearer to get the token securely

    This extracts the token from the request headers.
  2. Step 2: Decode the token to get user roles and check if 'admin' is present

    If the user is not an admin, raise HTTPException to deny access.
  3. Final Answer:

    Extract token with OAuth2PasswordBearer, decode user roles, and raise HTTPException if role is not 'admin' -> Option A
  4. Quick Check:

    RBAC requires role check after token extraction [OK]
Quick Trick: Decode token roles and restrict access by role inside route [OK]
Common Mistakes:
MISTAKES
  • Allowing all roles without checks
  • Checking roles from unsafe query parameters
  • Not raising exceptions for unauthorized roles

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes