Bird
0
0

What is wrong with this FastAPI role check code?

medium📝 Debug Q7 of 15
FastAPI - Authentication and Security
What is wrong with this FastAPI role check code?
async def role_check(user: User = Depends(get_current_user)):
    if 'admin' not in user.roles:
        raise HTTPException(status_code=403)
    return true

@app.get('/admin')
async def admin_route(allowed=Depends(role_check)):
    if not allowed:
        return {'error': 'Access denied'}
    return {'msg': 'Welcome admin'}
AThe dependency should return false instead of raising exception
BThe user roles should be checked synchronously
CDepends should not be used in async functions
DThe endpoint's if check is redundant because exception stops execution
Step-by-Step Solution
Solution:
  1. Step 1: Analyze dependency behavior

    The dependency raises HTTPException if unauthorized, stopping endpoint execution.
  2. Step 2: Check endpoint logic

    The if not allowed check is never reached if unauthorized, so it is redundant.
  3. Final Answer:

    The endpoint's if check is redundant because exception stops execution -> Option D
  4. Quick Check:

    Exception stops flow, no need for extra checks [OK]
Quick Trick: Raise exception to stop flow; no extra checks needed [OK]
Common Mistakes:
MISTAKES
  • Adding redundant checks after raising exception
  • Returning false instead of raising exception
  • Misunderstanding async Depends usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes